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; check the manual that corresponds to your ?MySQL server version for the right syntax to use near '\\\\'alex\\',\\\\'john\\\\')' ?at line 1"
How to correct use mysqli_real_escape_string
in WHERE IN
clause?
Try like this to prepare your $users variable,
$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.
$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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.