I’ve been having some trouble using an IN in a where clause using MySQLi this is my query:
SELECT * FROM core_tags WHERE tag_id IN (1,2,3,4,5) GROUP BY tag_id ORDER BY tag_popularity ASC
If I run this in PHP My Admin then I get 5 results as I would expect. However if I run it in PHP with the following code I only get one result of the tag_id ‘1’.
Here’s my PHP. Originally I was running it using functions in a class but I’ve hand coded it to test that it wasn’t simply an error in my functions with the same problem.
$mysqli = new mysqli(DB_SERVER, DB_NAME, DB_PASSWORD, DB_NAME);
$rawQuery = 'SELECT * FROM core_tags WHERE tag_id IN (?) GROUP BY tag_id ORDER BY tag_popularity ASC';
$stmt = $mysqli->prepare($rawQuery);
$stmt->bind_param("s", $tag_ids);
$tag_ids = "1,2,3,4,5";
$stmt->execute();
$stmt->bind_result($tag_id, $tag_name, $tag_desc, $tag_popularity);
while ($stmt->fetch()) {
printf ("%s\n", $tag_name);
}
$stmt->close();
die();
Anyone have any idea why the mysqli version only returns one row? Using MySQL instead of mysqli works fine as well, same as PHP My Admin.
Using a string prepared statement will cause your final SQL to look like:
with the quotes, which is not what you want. What I’d do is this:
If the
implode array_fillis confusing, it just is a shorthand way of creating an array of the same size as$idsfull of"?", then turning them to a csv.UPDATE: Non bind params way
Of course, if you want to skip the bind params nonsense, and you can trust the list of
$idsto already be sanitized, you can just do this instead, and skip the bind_params section:If you can’t trust the data: