Import csv file in MySQL using PHP

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.";
?> ```

Upvotes: 0

Views: 88

Answers (1)

user1360618
user1360618

Reputation:

You have an error in this line:

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

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

Upvotes: 1

Related Questions