I have multiple numeric values which I can express as either an array, or as a comma-separated string. For each of these values I would like to select the corresponding database row. Is it possible to do this in one query?
// data examples
$array = array(3, 6, 200); // or more values
$string = '3,6,200' ; // or more values
I can do the following query for each value, to get a field from the table:
SELECT email FROM table WHERE id='$array_value';
But how can I get this in one query?
You should use IN
operator. If $data
is either array or comma separated list of numbers (string), do:
$in = is_array($data) ? implode(',', $data) : $data;
$query = "SELECT email FROM table WHERE id IN (" . $in . ")";
Only do this if you are sure that elements in the array are safe.
If you have to make your data safe you can do this
$in = is_array($data) ?
"'" . implode("','", array_map('mysql_real_escape_string', $data)) . "'" :
"'" . mysql_real_escape_string($data) . "'";
Or if you are expecting integer values, just go with:
$in = is_array($data) ?
implode(',', array_map('intval', $data)) :
(int)$data;
Try using IN
.
$query = 'SELECT email FROM table WHERE id IN (' . ( is_array( $ids ) ? implode( ',', $ids ) : $ids ) . ')';
Assuming $ids
is the list of IDs as either a string or an array.
// $vals is your "array or comma-separated string"
if( is_array($vals)) $vals = implode(",",$vals);
mysql_query( "SELECT `id`, `email` FROM `table` WHERE `id` IN (".$vals.")");
I selected id
as well so that you can identify which email belongs to which ID when you loop through the results. If this is not important, you can drop it.