Home > database >  Convert String containing commas to array
Convert String containing commas to array

Time:05-10

I am trying to convert a String

$string = "'1', '2', '3'";` 

to an array

$array = array($string);

By doing so it gives me an error when trying to fetch data on MySQL

SELECT * FROM name WHERE id NOT IN ( '" . implode( "', '" , $array) . "' ) LIMIT 10 

However, if I manually set the array as $array = array('1', '2', '3') it doesn't give an error when fetching a data, is there a way to convert the string to the array so the fetching doesn't give out an error? Because what I am trying to do is some data will be going to be passed to this file, where it will be fetched as a String, but later want to convert it to an array. I also tried removing the quotation mark from the String and it still gives the same error str_replace('"', "", $string); using this inside of the array.

CodePudding user response:

if you remove the quotes around the id's, assuming the id column is a integer column

$string = "'1', '2', '3'"; 
$string = str_replace("'", '', $string);

$sql = "SELECT * FROM name WHERE id NOT IN ( " . implode(",", explode(',',$string)) . ") LIMIT 10 ";
echo $sql;

RESULT

SELECT * FROM name WHERE id NOT IN ( 1, 2, 3) LIMIT 10 

Of course a simpler way would be to simply do

$string = "'1', '2', '3'"; 
$string = str_replace("'", '', $string);
$sql = "SELECT * FROM name WHERE id NOT IN ( $string ) LIMIT 10 ";
  • Related