2016-05-13 209 views
-1

試圖在將用作查詢的字符串變量內插入變量。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

回答

0

實際上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; 
} 
0

你可能需要在你的變量名單引號中查詢:

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

WHERE staff.staffID = '$staffID'