2

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

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
NULL
  • 1,559
  • 5
  • 34
  • 60

3 Answers3

7
'SELECT ... WHERE id IN ("' . implode('","', $strings) . '")';
hsz
  • 148,279
  • 62
  • 259
  • 315
  • Works really well! I want to ask a question, what are the dots exactly doing, are they acting like "+" to glue the quotes with the implode result? – deckoff Oct 29 '12 at 20:44
1

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) . '");';
Crozin
  • 43,890
  • 13
  • 88
  • 135
0
implode("','",$array);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345