1

I have a simple array in PHP, say

[1, 2, 4, 5, 6, 7]

and I wish to query a MYSQL database

[1, who]
[2, where]
[3, some]
[6, there]
[9, too]

I only wish to receive the rows of intersection between the PHP array and the database's indices column. So this would result in

[1, who]
[2, where]
[6, there]

Any ideas? Thanks!

1 Answer 1

4

You want the sql in keyword

SELECT id, title FROM tablename WHERE id IN (1, 2, 4, 5, 6, 7)

You can prepare the list of numbers using:

$nums = array(1, 2, 4, 5, 6, 7)
$sql = 'SELECT id, title FROM tablename WHERE id IN (' . implode(',', $nums) . ')';

Edit: you can make sure your input contains only numbers with array_filter:

$nums = array_filter($nums, 'is_numeric');
Sign up to request clarification or add additional context in comments.

4 Comments

Might want to add a giant disclaimer about the dangers of SQL injection somewhere...
Thank you very much, both of you. I knew about the IN operator, but as soon as you posted I knew what to do. I will also be sure to check the injection vulnerability.
Thanks, added array_filter to ensure $nums only contains numbers
@ Dominic Rodger: i don't see any user input, so a giant disclaimer about the dangers of SQL injection seems to be a little inappropriate here.

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.