Reputation: 77
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?
Upvotes: 1
Views: 3154
Reputation: 64
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";
Upvotes: 3