Using in in where

I am having problems using IN in a where clause using MySQLi. This is my request:

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, I get 5 results, as expected. However, if I run it in PHP with the following code, I will get only one result tag_id '1'.

Here is my php. I initially ran it using functions in the class, but I manually coded it to verify that this is not just 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();

Does anyone have any ideas why the mysqli version returns only one row? Using MySQL instead of mysqli also works just fine, as does PHP My Admin.

+3
source share
2 answers

, , , SQL :

IN ('1,2,3,4,5')

, , . :

$ids= array(1,2,3,4,5);
$mysqli = new mysqli(DB_SERVER, DB_NAME, DB_PASSWORD, DB_NAME);

$rawQuery = 'SELECT * FROM core_tags WHERE tag_id IN (';
$rawQuery .= implode(',',array_fill(0,count($ids),'?'));
$rawQuery .= ') GROUP BY tag_id ORDER BY tag_popularity ASC';
$stmt = $mysqli->prepare($rawQuery);
call_user_func_array(array($stmt,'bind_param'),$ids);
$stmt->execute();
$stmt->bind_result($tag_id, $tag_name, $tag_desc, $tag_popularity);

while ($stmt->fetch()) {
    printf ("%s\n", $tag_name);
}

implode array_fill , , $ids, "?", csv.

UPDATE: params

, , $ids, , bind_params:

$rawQuery = 'SELECT * FROM core_tags WHERE tag_id IN (';
$rawQuery .= implode(',',$ids);
$rawQuery .= ') GROUP BY tag_id ORDER BY tag_popularity ASC';

:

function clean_ids(&$item){
 $item = intval($item);
}

$clean_ids = array_walk($ids,'clean_ids');
$rawQuery = 'SELECT * FROM core_tags WHERE tag_id IN (';
$rawQuery .= implode(',',$clean_ids);
$rawQuery .= ') GROUP BY tag_id ORDER BY tag_popularity ASC';
+3

PHP, , , , , "IN", - :

* core_tags WHERE tag_id IN ('1,2,3')

, ... IN,

+2

Source: https://habr.com/ru/post/1755067/


All Articles