[英]Got error on using mysqli_real_escape_string in WHERE IN clause
I'm working on existing project and there is an abstraction layer on database (previous developers made it and I should not change it). 我正在处理现有项目,并且数据库上有一个抽象层(以前的开发人员已经做到了,我不应该更改它)。 I extracted functions from abstraction and it looks like this:
我从抽象中提取了函数,它看起来像这样:
$sql = "SELECT id FROM user WHERE username IN ({users})";
$users = "alex,john";
$users = str_replace(',', "','", $users);
$users = mysqli_real_escape_string($dbh, $users);
//Here is a replace placeholder function for sql query
...
$query = mysqli_query($dbh, $sql);
And I got an error: 我得到一个错误:
You have an error in your SQL syntax;
您的SQL语法有误; check the manual that corresponds to your ?MySQL server version for the right syntax to use near '\\\\'alex\\',\\\\'john\\\\')' ?at line 1"
检查与您的MySQL服务器版本相对应的手册,以在第1行的'\\\\'alex \\',\\\\'john \\\\')'附近使用正确的语法。
How to correct use mysqli_real_escape_string
in WHERE IN
clause? 如何在
WHERE IN
子句中正确使用mysqli_real_escape_string
?
Try like this to prepare your $users variable, 像这样尝试准备$ users变量,
$users = "alex,john";
$users= "'".str_replace(",", "','", $users)."'";
Edit: 编辑:
$users_array= explode(',',$users);
$users= "'". implode("', '", array_map('mysql_real_escape_string', $users_array)). "'";
Try this: 尝试这个:
$users = "alex,john";
$users = "'" . str_replace(',', "','", $users) . "'";
$users = mysqli_real_escape_string($dbh, $users);
$sql = "SELECT id FROM user WHERE username IN ({$users})";
$query = mysqli_query($dbh, $sql);
Recommended way is to use prepared statements instead and not worry about escaping special characters or SQL injection. 推荐的方法是改用准备好的语句,而不用担心转义特殊字符或SQL注入。
$users = "alex,john";
$users = "'" . str_replace(',', "','", $users) . "'";
$sql = "SELECT id FROM user WHERE username IN ({$users})";
$stmt = $dbh->prepare($sql);
$stmt->bind_param('s', $users);
$stmt->execute();
$results = $stmt->fetch();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.