dougang1967 2013-05-21 21:59
浏览 39
已采纳

如何在Inner Join MYSQL查询中使用PHP变量?

I have been trying for the past day to get mysql to recognize my PhP variable, but I have had no luck so far.

The code:

...connect to db...
session_start();
//Calls up Session stored variable
$currentUsr= $_SESSION['username'];
//SQL Query
$sql= 'SELECT Users.Username, books.* FROM Users
       INNER JOIN UserLinkBooks lb
       ON Users.Username = lb.Username
       INNER JOIN Books
       ON lb.bkTitle = books.Title
       WHERE Users.Username = "$currentUsr"';
$result=mysqli_query($conn,$sql);                                                                
//Error Check
if (!$result) {                                                                                   
   printf("Error: %s
", mysqli_error($conn)); 
   exit();}
//display row
while($row=mysqli_fetch_array($result)){                                                                                                        
    echo "<strong>".$row['Title']."</strong>".$row['Description']."</br>";}   

My issue is that the $currentUsr is not properly calling the username that was passed. After doing an error check on it, it seems to be empty.

What I do not understand is that when I use the code :

$sql = "SELECT * FROM Users WHERE `Username`='$currentUsr'";

The variable is processed and works fine, calling up the book title's and description perfectly. Also, if I manually type in: WHERE Users.UserName = "Bill"'; It works fine.

Some of the other errors I've gotten from various attempts are:

  WHERE Users.UserName = '.'$currentUsr';
  Error: Unknown column '$currentUsr' in 'where clause'

or

  WHERE Users.UserName = '.$currentUsr;  
  Error:  Unknown column 'Bill' in 'where clause'

Any help would be greatly appreciated. Thanks

  • 写回答

3条回答 默认 最新

  • dpf7891 2013-05-21 22:02
    关注

    Your variable is in a single quoted string, preventing interpolation. You can try:

    $sql = "SELECT Users.Username, books.* FROM Users
            INNER JOIN UserLinkBooks lb
            ON Users.Username = lb.Username
            INNER JOIN Books
            ON lb.bkTitle = books.Title
            WHERE Users.Username = '" . $currentUsr ."'";
    

    Using concatenation makes the code more readable in my opinion. Having said that, you should look into using parameterized queries as they cut down on injection issues. Mysqli has such capabilities.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀