-1

I have this sql query.

  select something from sometable WHERE `word` IN ('stand','on','in') GROUP BY (`p_id`)  LIMIT 1000

And I have a php variable ($words) which holds a sentence. How to pass that variable value into this IN clause?

ex: $words = "stand on in this here";

Asanka sanjaya
  • 1,461
  • 3
  • 17
  • 35

1 Answers1

1
$array = explode(" ", $words); // GEt each word in array
$in_stmt = "'".implode("','", $array)."'"; // create a string like 'stand','on','in'

BETTER:

$in_stmt = "'".str_replace(" ", "','", $words)."'";

MySQL Statement:

$stmt = "select something from sometable WHERE `word` IN (".$in_stmt.") GROUP BY (`p_id`)  LIMIT 1000"
Jigar
  • 3,256
  • 1
  • 30
  • 51
  • Welcome. Check my updated post. That is more efficient. – Jigar May 05 '14 at 18:17
  • By the way in my $words variable contains apostrophes and commas some times. Then the query will be injected. How can I get rid of that? – Asanka sanjaya May 05 '14 at 18:30
  • before string replace you can use `mysql_real_escape_string` or `mysqli_real_escape_string` refer docs for more details. http://in2.php.net/manual/en/mysqli.real-escape-string.php and http://in2.php.net/manual/en/mysqli.real-escape-string.php – Jigar May 05 '14 at 18:39
  • But I'm using cakephp. In cake php I cannot use real_escape_string function. What can I do? – Asanka sanjaya May 05 '14 at 18:44
  • I am not familiar with cakephp. If I am not wrong cakephp is just a framework. It should allow php mysql functions. And you can also check `addslashes` and `strpslashes`. But I am not sure if it will work for you. – Jigar May 05 '14 at 18:51
  • Ok. Thank you for helping me. I'll try those functions. – Asanka sanjaya May 05 '14 at 19:01