up vote 1 down vote favorite

i am building a string that i check in mysql db.

eg:
formFields[] is an array - input1 is: string1
array_push(strings, formFields)
1st string and mysql query looks like this:
"select * from my table where id in (strings)"

formFields[] is an array - input2 is: string1, string2
array_push(strings, formFields)
2nd string and mysql query looks like this:
"select * from my table where id in (strings)"

formFields[] is an array - input3 is: string1, string2,string3
array_push(strings, formFields)
3rd string and mysql query looks like this:
"select * from my table where id in (strings)"

i will like to add single quotes and a comma to the array so that i have this for the array strings: "select * from my table where id in ('string1', 'string2','string3')"

i tried using array implode, but still no luck any ideas? thanks

flag

65% accept rate

3 Answers

up vote 1 down vote accepted
'SELECT ... WHERE id IN ("' . implode('","', $strings) . '")';
link|flag
thank you! works like a charm. – Chocho Apr 14 at 13:50
up vote 0 down vote
implode("','",$array);
link|flag
this doesn't add a quote before and after the very beginning and end of the strings. thanks anyway! – Chocho Apr 14 at 13:51
@Chocho you don't know concatenation too? You desperately need basic PHP classes then. – Col. Shrapnel Apr 15 at 6:12
up vote 0 down vote

implode() is the solution but you shouldn't forget about escaping data:

$data = array(...);
array_walk($data, function(&$elem, $key) {
    $elem = mysql_real_escape_string($elem);
});
$sql = 'SELECT ... id IN ("' . implode('", "', $data) . '");';
link|flag
thank you also, your answer works too! – Chocho Apr 14 at 13:50

Your Answer

get an OpenID
or
never shown

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