Nixoderm
Nixoderm

Reputation: 355

how to add apostrophe in string

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

Answers (4)

Thamil Vaanan
Thamil Vaanan

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

Saf
Saf

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

Professor Abronsius
Professor Abronsius

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

Devsi Odedra
Devsi Odedra

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

Related Questions