PHP/SQL查询 - 在字符串变量内插入变量

问题描述:

试图在将用作查询的字符串变量内插入变量。PHP/SQL查询 - 在字符串变量内插入变量

$staffID = $_GET["staffID"]; 

    $conn = mysqli_connect("localhost", "twa095", "twa095de", "factory095"); 

    if (!$conn) 
    { 
    die("Connection failed: " . mysqli_connect_error()); 
    } 

    $sql = "SELECT staffName, orderID, orderDate, shippingDate 
    FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID 
    WHERE staffID = $staffID // Problem is over here. 
    GROUP BY orderDate" 

    $results = mysqli_query($conn, $sql) 
    or die ('Problem with query' . mysqli_error($conn)); 

    ?> 

闻听此事的错误:

问题与queryColumn“ STAFFID”在where子句是暧昧

此外,有没有一种方法,我可以把它检查是否给定的“ STAFFID” (第一行)在数据库内部,如果它不终止脚本并在它下面的所有内容执行之前显示错误消息?

+0

你会得到什么错误? –

+0

哪一行是26行? – Dale

+0

@FurqanAziz在原帖中添加了错误信息。 – Blocker

实际上staffID存在于两个连接表(购买和工作人员)中。 Mysql很困惑,staffID来自购买表或员工表。要解决你的问题添加tablename.staffID查询的WHERE子句中:

$sql = "SELECT staffName, orderID, orderDate, shippingDate 
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID 
WHERE staff.staffID = '{$staffID}' // Problem is over here. 
GROUP BY orderDate" 

Also as a best practice add {} around the variable inside another string and single quotes in case variable is empty it will work fine.

其次,对于检查,如果员工ID已在表并返回错误,你必须使用mysqli_num_rows() if子句中和打印错误消息的用户为:

$sql = "SELECT staffName, orderID, orderDate, shippingDate 
FROM purchase INNER JOIN staff ON purchase.staffID = staff.staffID 
WHERE staff.staffID = $staffID // Problem is over here. 
GROUP BY orderDate" 

$results = mysqli_query($conn, $sql) 
or die ('Problem with query' . mysqli_error($conn)); 

if(mysqli_num_rows($conn,$result)>0){ 
    echo "Error Message"; 
    exit; 
} 

你可能需要在你的变量名单引号中查询:

WHERE staff.staffID = $staffID // Problem is over here. Should change to:

WHERE staff.staffID = '$staffID'