Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows from a MySQL table where value is an array?

Tags:

php

mysql

I have a table with a list of IDs. I use a query to select that and then fetch it as an array (I know how to do this). Then I want to select rows from another table where the IDs are in the array fetched earlier.

How would I do this? Thanks in advance.

like image 574
iamandrus Avatar asked Dec 17 '22 15:12

iamandrus


1 Answers

You'd most likely want to do a WHERE field IN (...) type query. It's essentially the equivalent of WHERE field=X or field=Y or field=Z or ... for every value listed in the IN clause.

Given that you've got an array of IDs already, the simplest way is to build the query like this:

$where_in = implode(',', $ids_array);

$query = "SELECT ... FROM yourtable WHERE idfield IN ($where_in);";

The usual provisos apply - be careful about SQL injection holes, always check query results for failure, etc...

like image 128
Marc B Avatar answered Dec 19 '22 07:12

Marc B