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
  • 4
  • 23

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
  • 33,063
  • 5
  • 32
  • 46
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
  • 318
  • 3
  • 13
-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,244
  • 1
  • 23
  • 37