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

时间:2016-05-13 14:20:18

标签: php mysql

尝试在将用作查询的字符串变量中插入变量。

    $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));

    ?>

将此视为错误:

where子句不明确的queryColumn'staffID'问题

另外,有没有办法可以检查给定的“staffID”(第一行)是否在数据库内部,是否终止脚本并在其下面的所有内容执行之前显示错误消息? / p>

2 个答案:

答案 0 :(得分:0)

实际上staffID存在于两个联合表(购买和员工)中。 Mysql很困惑,staffID来自购买表或员工表。要解决您的问题,请将tablename.添加到查询的where子句中的staffID

$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"
  

另外,最佳做法是在另一个变量中添加{}   在case变量为空的字符串和单引号中它将正常工作。

其次,为了检查人员ID是否已经在表中并返回错误,您必须在if子句中使用mysqli_num_rows()并向用户输出错误消息:

$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;
}

答案 1 :(得分:0)

您的查询中可能需要在变量名称周围添加单引号:

  

WHERE staff.staffID = $ staffID //问题已经结束了。   应改为:

WHERE staff.staffID = '$staffID'