0

I had a value like this $x = 'LA1,LA2,LA3,LA7';

And I want to this value to be execute in my sql. I know it will return error because missing '' in each id's. example 'LA1','LA3','LA7' How to add this symbol so query can execute? Any idea?

$sql = 'SELECT * FROM tbl WHERE id IN ("'.$x.'")';
Nixoderm
  • 355
  • 3
  • 20

4 Answers4

1

Using a combination of explode and implode ought to work

$x = 'LA1,LA2,LA3,LA7';
$sql = sprintf('SELECT * FROM tbl WHERE id IN ("%s")', implode( '","', explode(',',$x) ) );
Professor Abronsius
  • 30,177
  • 5
  • 29
  • 43
1

Ill suggest to put in array rather than keeping it in a string,

$variables = array('apple','orange','kiwi');
$variables = implode("','",$variables );

$sql = 'SELECT * FROM tbl WHERE id IN ('{$variables}')';
0

split it to array then add apostrophe

$x = 'LA1,LA2,LA3,LA7';
$arrayX = explode(',', $x);
$sql = 'SELECT * FROM tbl WHERE id IN ("'.implode('",', $arrayX).'")';

Saf
  • 198
  • 2
  • 11
-1

You need explode() and join()

$x = 'LA1,LA2,LA3,LA7';
$x = explode(",", $x);
$x= join("', '", $x);
$sql = "SELECT * FROM tbl WHERE id IN ('$x')";
Devsi Odedra
  • 5,071
  • 1
  • 21
  • 33