1

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?

3 Answers 3

4

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;
3
  • values are checkboxes id attr this is secure? if not , how can i do it?
    – MikZuit
    Feb 24, 2012 at 17:40
  • no, that is definitely not secure, will update the answer in a sec.
    – gintas
    Feb 24, 2012 at 18:17
  • After assigning $in, use array_walk( $in, 'intval' );
    – kitti
    Feb 24, 2012 at 18:20
2

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.

1
// $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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.