0

I need to select multiple rows in db (using MYSQL). I create the following query by iterating over array of ids:

$ids = array(1,2);
$idq = array();
$q = "SELECT * FROM table_name WHERE ";
foreach($ids as $id)
{
    $idq[] = "`ID` = '" . $id . "'";
}

$q .= implode(" AND ", $idq);

SELECT * FROM table_name WHERE `ID` = '1' AND `ID` = '2'

For some reason it doesn't seem to work:

The above won't work. Is there a better way?

When I do:

`SELECT * FROM table_name WHERE `ID` = '1'`

It works fine but when I add the AND ID = '2' it won't work at all.

0

3 Answers 3

2

Use WHERE IN

SELECT * FROM table_name WHEREIDIN ('1', '2')

Sign up to request clarification or add additional context in comments.

Comments

2
SELECT * FROM table_name WHERE `ID` = '1' AND `ID` = '2'

The ID cannot be 1 and 2 at the same time. You should use OR.

SELECT * FROM table_name WHERE `ID` = '1' OR `ID` = '2'

or

SELECT * FROM table_name WHERE `ID` IN (1,2,...)

Comments

0

SELECT * FROM table_name WHERE ID = '1' AND ID = '2'

You are saying: I want to go to the beach and to skiing at 5pm of the same day. Result: not possible. You can either go to the beach or to skiing. so your query should look like:

SELECT * FROM table_name WHERE ID = '1' OR ID = '2' or SELECT * FROM table_name WHERE ID in (1,2)

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.