lundi 13 juin 2016

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 attempt: 2.1 i try to change the names to arrays by using this code

$myString = "Red,Blue,Black";
$myArray = explode(',', $myString); 

2.2 and i try my insertion like this:

$sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
            if (!$result = $mysqli->query($sql)){
                    $message = array('Message' => 'insert fail');
                    echo json_encode($message);         
            }else{             
                    $message = array('Message' => 'new record inserted');
                    echo json_encode($tempArray);     
            }

Here is my complete code view

 <?php
define('HOST','serveraddress');
define('USER','root');
define('PASS','pass');
define('DB','dbname');
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

            $mysqli = new mysqli(HOST,USER,PASS,DB);
    $message= array();      
        $myString = "Red,Blue,Black";// incoming string comma names
        $myArray = explode(',', $myString); 

       $sql="INSERT INTO `cat_interest`(`id`,`categories`) VALUES (1,'".$myArray["categories"]."'";
                if (!$result = $mysqli->query($sql)){
                        $message= array('Message' => 'insertion failed');
                        echo json_encode($message);         
                }else{             
                        $message= array('Message' => 'new record inserted');
                        echo json_encode($message);   
                } ?>

This is what i want to achieve below
TABLE
ID     Categories
1        RED
1        Blue
1        Black

after insertion

Please help i don't know what i doing wrong

Aucun commentaire:

Enregistrer un commentaire