0

I have a CSV file with the folowing data and I want to upload it to a Mysql database

BGYR002217;FK-066 BGYR002218;FK-140

and I get this error:

Warning: Undefined array key 2 in C:\xampp\htdocs\test\import.php on line 21 SQLSTATE[42000]: Syntax error or access violation: 1064 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 ';NULL)' at line 1 Warning: Undefined array key 1 in C:\xampp\htdocs\test\import.php on line 21

My code:

$dbHost = 'localhost';
$dbName = 'test';
$dbChar = 'utf8';
$dbUser = 'root';
$dbPass = '';
try {
  $pdo = new PDO(
    "mysql:host=".$dbHost.";dbname=".$dbName.";charset=".$dbChar,
    $dbUser, $dbPass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
  );
} catch (Exception $ex) { exit($ex->getMessage()); }
 
$fh = fopen($_FILES["upcsv"]["tmp_name"], "r");
if ($fh === false) { exit("Failed to open uploaded CSV file"); }
 
while (($row = fgetcsv($fh)) !== false) {
  try {

    $stmt = $pdo->prepare("INSERT INTO users (szam, forras_szam) VALUES (?;?)");
    $stmt->execute([$row[0], $row[1]]);
  } catch (Exception $ex) { echo $ex->getmessage(); }
}
fclose($fh);
echo "DONE.";
?> ```

1 Answer 1

1

You have an error in this line:

$stmt = $pdo->prepare("INSERT INTO users (szam, forras_szam) VALUES (?;?)");

It should read: VALUES (?,?) and not VALUES (?;?)

Sign up to request clarification or add additional context in comments.

3 Comments

Now this erro come up: Warning: Undefined array key 1 in C:\xampp\htdocs\test\import.php on line 21 SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'forras_szam' cannot be null
'Undefined array key 1' probably means that $row[1] is not set, either because the $row array has either zero or only one element.
The standard column separator of fgetcsv is comma, but your column separator in you csv string seems to be the semicolon, so you need to tell that to fgetcsv: while (($row = fgetcsv($fh, 0, ';')) !== false) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.