Created
May 11, 2014 13:00
-
-
Save stavrossk/0f513ccbfe7882870ab1 to your computer and use it in GitHub Desktop.
Import a CSV file into a MySQL database using PHP PDO.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; | |
?> |
same here i your code connot detect my csv file ..
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.
It's works!!! thank you so much
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
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.