skip to Main Content

If I use a standard query, like
"LOAD DATA LOCAL INFILE ‘./uploads/import.csv’ INTO TABLE table1 FIELDS TERMINATED BY ‘;’ LINES TERMINATED BY ‘n’"

the file is imported successfully. If, however, I pass the table name as a variable in PHP, MariaDB complains that I have an error in my code. MariaDB objects to the following code:

$table = 'table1';
$updateTable = "LOAD DATA LOCAL INFILE './uploads/import.csv' INTO TABLE '$table' FIELDS TERMINATED BY ';'  LINES TERMINATED BY 'n'";
if (mysqli_query ($dbc, $updateTable))
{
$message1 = 'The ' . $table . '  was updated successfully.';
}

I used Eclipse to debug the code I mentioned with the latest version of PHP 8.2.4:

And I got this error: Fatal error: Uncaught mysqli_sql_exception: 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 ”table1′ .

However, the debugger expanded the $updateTable string as:

"LOAD DATA LOCAL INFILE ‘./uploads/import.csv’ INTO TABLE table1 FIELDS TERMINATED BY ‘;’ LINES TERMINATED BY ‘n’", which is the same string that resulted in a successful query by MariaDB when not using the passed $table variable in PHP. So I am apparently missing something or haven’t had enough coffee today…

2

Answers


  1. So there incorrect concatenation in your SQL string i believe it should be

    $updateTable = "LOAD DATA LOCAL INFILE './uploads/import.csv' INTO TABLE $table FIELDS TERMINATED BY ';' LINES TERMINATED BY 'n'";
    

    use a period (.) to concatenate strings in PHP, but without the dots around the variable.

    Edit:
    Make sure that the variable $dbc contains the valid database connection, and the file path ‘./uploads/import.csv’ is correct. Please refrain from editing code piece after an answer is given.

    Login or Signup to reply.
  2. The name of a table is an identifier, not a string literal. You must not put identifiers in single-quotes as if they are strings.

    INCORRECT:

    LOAD DATA LOCAL INFILE './uploads/import.csv' INTO TABLE '$table'
    

    CORRECT:

    LOAD DATA LOCAL INFILE './uploads/import.csv' INTO TABLE $table
    

    ALSO CORRECT:

    LOAD DATA LOCAL INFILE './uploads/import.csv' INTO TABLE `$table`
    

    Identifiers may be in back-ticks (not single-quotes), and this is needed if the identifier name conflicts with a reserved keyword, or if it contains whitespace or most punctuation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search