当我在 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);
}
我知道错误不是来自 session 变量,但如果是来自 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
模式是最糟糕的错误处理方式。您最好提出异常并在可以从中恢复的地方捕获它们并提供用户友好的消息。
关于SQL语句中的PHP变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21590511/