1

I'm trying to import an CSV into mySQL, I'm very new to this, but to my knowledge I've followed exactly what another post on stackoverflow has said and it's still not working.

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

 $query = <<<eof
 LOAD DATA INFILE 'hi.csv'
 INTO TABLE testing
 FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
 LINES TERMINATED BY '\n'
(firstname)
eof;

$db->query($query);

?>

If anyone could help it would be greatly appreciated. With the current code, the error is "Parse error: syntax error, unexpected end of file in (filename) on line 24. But even when error free, it doesn't put new data into mySQL.

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
Matt H
  • 91
  • 6

1 Answers1

0

According to the manual, the INFILE command specifically looks for a file in the folder containing the database on the server. If the command is failing, it is possibly due to this file not being in the correct location, because the rest of your code looks correct to me. Do you have access to place your file into that folder directly?

If not, you will need to update your approach to load the file from a directory you own.

In that case, I would use fgetcsv and a loop to load the data. You can see the example code on the PHP Manual page I have linked, and replace the inner portion of the loop to load a row of data instead displaying the data.

colonelclick
  • 2,165
  • 2
  • 24
  • 33
  • Simply adding -- $query = file_get_contents('the csv file'); within my current code, or completely rewriting it? – Matt H Jun 15 '18 at 13:26