Skip to content

Instantly share code, notes, and snippets.

@stavrossk
Created May 11, 2014 13:00
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stavrossk/0f513ccbfe7882870ab1 to your computer and use it in GitHub Desktop.
Save stavrossk/0f513ccbfe7882870ab1 to your computer and use it in GitHub Desktop.
Import a CSV file into a MySQL database using PHP PDO.
<?php
$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";
if(!file_exists($csvfile))
{
die("File not found. Make sure you specified the correct path.");
}
try
{
$pdo = new PDO(
"mysql:host=$databasehost;dbname=$databasename",
$databaseusername,
$databasepassword,
array
(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
}
catch (PDOException $e)
{
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec
(
"LOAD DATA LOCAL INFILE "
.$pdo->quote($csvfile)
." INTO TABLE `$databasetable` FIELDS TERMINATED BY "
.$pdo->quote($fieldseparator)
."LINES TERMINATED BY "
.$pdo->quote($lineseparator)
);
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
@Lisud
Copy link

Lisud commented May 12, 2016

Excuse me, I'm trying to use your code but it doesn't find my file, so can you explain me, where I should save the file for it to find it, please?

I'm using xampp in my local computer, tried to save in the main folder of xampp and also in the folder where I'm working with code but didn't get any result yet.

Thank you so much.

@labmeeter
Copy link

same here i your code connot detect my csv file ..

@Lordicon
Copy link

Lordicon commented Dec 5, 2017

I know its an old question but change this line "$csvfile = "filename.csv";" to your own files name and place it in the same directory as the .php file.

@TheBrown
Copy link

It's works!!! thank you so much

@hariomjee
Copy link

really it work thank u so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment