简体   繁体   中英

SELECT * FROM table WHERE value IN array only return one result

I'm trying to get all posts from a table where the id is in an array. So, I have an array with 2 ids and the 2 ids have a post, but the query only returns the post from the first id.

This is my code with sample values:

$ides= array();
array_push($ides, '1, 2');
    $ids = implode(',',$ides);  
                $sql="SELECT * FROM post WHERE id IN ('$ids') ORDER BY date DESC";

Then, in this case, the result that I have is only the post where the id is "1". What am I doing wrong?

Your query returns only one result because you have enclosed both values into the single quotes. So your query looks like this

SELECT * FROM post WHERE id IN ('1, 2') ORDER BY date DESC

And it should look like this

SELECT * FROM post WHERE id IN (1,2) ORDER BY date DESC

If you run your initial query in mysql console, it'll probably show you a warning

mysql> select cast('1,2' as unsigned);
+-------------------------+
| cast('1,2' as unsigned) |
+-------------------------+
|                       1 |
+-------------------------+
1 row in set, 1 warning (0.01 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1292 | Truncated incorrect INTEGER value: '1,2' |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql>

To fix it, I suggest the following code

$ids = [1,2];
$ids_string = implode(',',$ids);
$sql="SELECT * FROM post WHERE id IN ($ids_string) ORDER BY date DESC";

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM