Reputation: 355
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.'")';
Upvotes: 0
Views: 312
Reputation: 11
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}')';
Upvotes: 1
Reputation: 318
split it to array then add apostrophe
$x = 'LA1,LA2,LA3,LA7';
$arrayX = explode(',', $x);
$sql = 'SELECT * FROM tbl WHERE id IN ("'.implode('",', $arrayX).'")';
Upvotes: 0
Reputation: 33804
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) ) );
Upvotes: 1
Reputation: 5322
You need explode()
and join()
$x = 'LA1,LA2,LA3,LA7';
$x = explode(",", $x);
$x= join("', '", $x);
$sql = "SELECT * FROM tbl WHERE id IN ('$x')";
Upvotes: -1