SQL语句中的PHP变量
在SQL语句中使用变量时,我收到以下错误:SQL语句中的PHP变量,php,mysql,sql,mysqli,Php,Mysql,Sql,Mysqli,在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;$lquery($query)或die($mysqli-
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;$lquery($query)或die($mysqli->error);
}
我知道错误不是来自会话变量,但是如果是来自l
,我不知道为什么。我认为我做的每件事都是正确的。我为什么会收到错误以及如何防止它?试试这个
$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']."' ";
还是这个
$query = "UPDATE members SET item'".$l+1."' = $itemID[$l]
WHERE ID = '".$_SESSION['id']."' ";
您的查询在没有正确转义的情况下混合了用户数据:
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();
}
for($l=0;$lprepare($query);
$stmt->bind_param('is',$itemId[$l],$_SESSION['id']);
/*执行并获得结果*/
$result=$stmt->execute();
}
或die
模式是处理错误的最糟糕的方式。您最好提出异常并在某个可以从中恢复的地方捕获这些异常,并显示一条用户友好的消息
for
循环和count($item)
多条UPDATE
语句
$query
,查看,并将其添加到您的问题中“
和”
这两种方法都会产生
…SET item 0+1=…
,这将是一个语法错误。实际上,我认为这仍然是一个问题。它们会产生类似…SET item'1'=…
,这也不起作用。使用mysqli
时,应该使用参数化查询,并将用户数据添加到查询中。不要使用字符串插值来完成此操作,因为您可能会创建严重的。非常好的答案;这是唯一解决注入问题和字段名问题的答案。我会重新设计架构,以避免出现名称如此糟糕的列,并避免循环更新。此设计违反了
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();
}
UPDATE members SET item1=value1, item2=value2, ... WHERE ID = ".$_SESSION['id'];