1

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?

1
  • It's surprising that it returns anything at all, since you're actually asking for a post where the ID is equal to 1,2 — but I guess MySQL's lax type conversion strikes again. Commented Dec 14, 2019 at 17:17

1 Answer 1

3

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.