PHP: Insert separated comma string value with as multiple array value Into MySql

前端 未结 1 1677
终归单人心
终归单人心 2021-01-29 00:49

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 att

相关标签:
1条回答
  • 2021-01-29 01:10

    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($myArray as $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.

    0 讨论(0)
提交回复
热议问题