Created
September 16, 2016 14:32
-
-
Save matusk/2828c98ed805ee0b2b84870bdcefdceb to your computer and use it in GitHub Desktop.
LOAD DATA INFILE (MySQL)
This file contains hidden or 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 | |
$dbHost = ''; | |
$dbName = ''; | |
$dbTable = ''; | |
$dbUser = ''; | |
$dbPassword = ''; | |
$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=' . $dbHost . ';dbname=' . $dbName, | |
$dbUser, | |
$dbPassword, | |
array( | |
PDO::MYSQL_ATTR_LOCAL_INFILE => true, | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, | |
) | |
); | |
} catch (PDOException $e) { | |
die('database connection failed: ' . $e->getMessage()); | |
} | |
// http://dev.mysql.com/doc/refman/5.7/en/load-data.html | |
$affectedRows = $pdo->exec( | |
'LOAD DATA LOCAL INFILE ' . $pdo->quote($csvFile) . ' ' . | |
'INTO TABLE `' . $dbTable . '` ' . | |
'FIELDS TERMINATED BY ' . $pdo->quote($fieldSeparator) . ' ' . | |
'LINES TERMINATED BY ' . $pdo->quote($lineSeparator) | |
); | |
echo 'Loaded a total of ' . $affectedRows . ' records from csv file.'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment