How do you output the contents of an array as a comma separated string?

I would like to convert the array, if IDs, to a comma separated string of values ​​for use in a MySQL UPDATE query. How should I do it?

+1


source to share


5 answers


Don't forget to store the values:



'"' . implode('","', array_map('mysql_real_escape_string', $data)) . '"'

      

+13


source


implode(',', $array);

      



+13


source


Make sure you pass the results through mysql_real_escape_string () before executing your query . This should prevent sql injection if you use implode () as others suggest.

And as nickf mentions, always check to make sure the array is not empty or null first, and handle those cases. Since you are only dealing with int, it doesn't hurt to check the type of your assignments, otherwise you will get sql errors if the string slips somehow.

+2


source


Often times this type of situation is people building an array from another table for use in a second query. If so, you can use a subquery to accomplish this.

Eg. UPDATE Table SET Column = ID value WHERE IDENTIFICATOR (SELECT ID from table2 WHERE CONDITIONS)

+1


source


It is probably best if all identifiers must be numeric. Make sure it consists of at least one integer with

$ids = array_filter($ids, 'is_int');
if (!$ids) {
    //no valid ids returned.
    die('or something');
}
$sql .= '(' . implode(',', $ids) . ')';

      

0


source







All Articles