Add quotes to values in a string separated by a comma php

I have a comma seprated string that can contain multiple values like charecter and number or any thing else. Now i am using this with the IN clause in sql query.

Let see example :

$str = "k, w, 1, 2, 3, 4, 5, 6, 7, 8";

Now i am running this with 'IN' clause in sql query like below :

QUERY = "SELECT * FROM tbl_user WHERE grade IN($str)";

When i run the above query its threw error because in my string k and w are charecter not a integer so its threw error. If i add a single inverted comma before and after each of the integer value then problem will be resolve. Like below :

$str = "'k', 'w', '1', '2', '3', '4', '5', '6', '7', '8'";

Solution : To do this in php you have to perform a simple sting replacement like below -

$str = "k, w, 1, 2, 3, 4, 5, 6, 7, 8";
$str =" ' ".  str_replace(",", "','", $str) ." ' ";
echo $str ;

OUTPUT :  It will return the string like this - 'k', 'w', '1', '2', '3', '4', '5', '6', '7', '8'
 
 Chears
Happy coding :)

Post a Comment

Previous Post Next Post