Skip to content Skip to sidebar Skip to footer

Php: Insert Separated Comma String Value With As Multiple Array Value Into Mysql

Here is my goal 1. I have only one ID send from the server with list of string separated comma this how it look like: ID=1, names=blue,red,green,yellow 2. This is my attemp

Solution 1:

While that SQL is invalid, you never close the values. Explode also doesn't build an associated array.

A rough example of how you could build a valid SQL statement would be

$myString = "Red,Blue,Black";// incoming string comma names$myArray = explode(',', $myString); 
print_r($myArray);
$sql = "INSERT INTO `cat_interest`(`id`,`categories`) VALUES";
foreach($myArrayas$value){
    $sql .= " (1, '{$value}'),";
}
$sql = rtrim($sql, ',');

Demo: https://eval.in/587840

When in doubt about how an array in constructed use print_r or var_dump. When having an issue with a query in mysqli use error reporting, http://php.net/manual/en/mysqli.error.php.

Also in your current usage you aren't open to SQL injections but if $myString comes from user input, or your DB you could be. You should look into using parameterized queries; http://php.net/manual/en/mysqli.quickstart.prepared-statements.php.

Post a Comment for "Php: Insert Separated Comma String Value With As Multiple Array Value Into Mysql"