[英]PHP Variable in SQL Statement
我在SQL語句中使用變量時收到以下錯誤:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 = 86 WHERE ID = 284' at line 1
SQL的代碼(PHP中正在使用)為:
for($l=0; $l<count($item); $l++) {
$query = "UPDATE members SET item" . $l+1 . " = ".$itemID[$l]." WHERE ID = ".$_SESSION['id'];
$result = $mysqli->query($query) or die($mysqli->error);
}
我知道錯誤不是來自會話變量,但是如果來自l
,我不知道為什么。 我以為我做的一切正確。 為什么會收到該錯誤以及如何防止該錯誤?
您的查詢混入了用戶數據而沒有適當的轉義:
for($l=0; $l<count($item); $l++) {
/* Use sprintf to avoid injecting arbitrary strings into query */
$query = sprintf("UPDATE members SET item%d=? WHERE ID=?", $l + 1);
/* Prepare the statement and bind specific user data values into placeholders */
$stmt = $mysqli->prepare($query);
$stmt->bind_param('is', $itemId[$l], $_SESSION['id']);
/* Execute and get result */
$result = $stmt->execute();
}
or die
模式是處理錯誤的最壞方法。 最好提起異常,並在可以從異常中恢復的地方捕獲異常,並提供用戶友好的消息。
$query = "UPDATE members SET item" . ($l+1) . " = ".$itemID[$l]." WHERE ID = ".$_SESSION['id'];
當您可以使用1(一個)執行循環時,沒有理由使用for
循環並使用count($item)
許多UPDATE
語句!
UPDATE members SET item1=value1, item2=value2, ... WHERE ID = ".$_SESSION['id'];
$query
,查看一下並將其添加到此處的問題中 。 "
和'
。 嘗試這個
$query = "UPDATE members SET item'".$l+1."' = '".$itemID[$l]." '
WHERE ID = '".$_SESSION['id']."' ";
或這個
$query = "UPDATE members SET item'".$l+1."' = $itemID[$l]
WHERE ID = '".$_SESSION['id']."' ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.