Search code examples
phpsqlmysqli-multi-query

Why does creating a table and then inserting multiple values return an error?


So I'm trying to create a table and then insert multiple values into it, like so:

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "someDbName";
        $conn = mysqli_connect($servername, $username, $password, $dbname);
                if (!$conn) {
                    die("Connection failed: " . mysqli_connect_error());
                }
                    $sql = "CREATE TABLE IF NOT EXISTS someTableName(
                    someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    someVar1 VARCHAR(30) NOT NULL,
                    someVar2 INT NOT NULL);
                    INSERT INTO someTableName (someVar1 , someVar2 ) VALUES ('someString1', someInteger1),
                    ('someString2',someInteger2);";

Where the someInteger bits are, of course, integers. And then:

            $sql = mysqli_real_escape_string($conn, $sql);    
            if (mysqli_multi_query($conn, $sql)) {
                dtconsole("Tables populated successfully");
            } else {
                dtconsole("Error creating table: " . mysqli_error($conn));
            }

With the dtconsole function there just to output to console to help me debug.

function dtconsole($data){
        $output=$data;
        if(is_array($output)){
            $output=implode(',',$output);
        }
        echo '<script>console.log("'.$output.'");</script>';
    } 

Every time I try to run this, it returns the following error:

Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, ' at line 1

And I can't for the life of me see what I'm doing wrong.


Solution

  • Your problem is that you are calling mysqli_real_escape_string on your entire query, instead of just the values you are inserting. As a result it is converting the CR-LF in your $sql string into \r\n, which the MySQL parser cannot interpret. You should be doing something like this:

    $someString1 = mysqli_real_escape_string($conn, 'someString1'); 
    $someString2 = mysqli_real_escape_string($conn, 'someString2');
    $sql = "CREATE TABLE IF NOT EXISTS someTableName(
            someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            someVar1 VARCHAR(30) NOT NULL,
            someVar2 INT NOT NULL);
            INSERT INTO someTableName (someVar1 , someVar2 ) VALUES ($someString1, someInteger1),
            ($someString2,someInteger2);";
    if (mysqli_multi_query($conn, $sql)) { 
        ...