user15063
user15063

Reputation:

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

I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?

Upvotes: 1

Views: 8956

Answers (5)

OIS
OIS

Reputation: 10033

This is probably better if all ids should be numerical. Check that 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) . ')';

Upvotes: 0

DreamWerx
DreamWerx

Reputation: 2909

Often this type of situation is people building an array from another table for use in a 2nd query.. If this is the case you can use a subquery to accomplish this.

Eg. UPDATE Table SET Column = Value WHERE ID IN ( SELECT ID FROM Table2 WHERE CONDITIONS )

Upvotes: 1

troelskn
troelskn

Reputation: 117427

Remember to escape values:

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

Upvotes: 13

Eran Galperin
Eran Galperin

Reputation: 86805

implode(',', $array);

Upvotes: 13

Dana the Sane
Dana the Sane

Reputation: 15198

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 isn't empty or null first, and handle those cases. Since you are only dealing with int's, it wouldn't hurt to put some type checking in your assignments, otherwise you'll get sql errors if a string slips in somehow.

Upvotes: 2

Related Questions