Skip to content

Instantly share code, notes, and snippets.

@LithionLabs
Created May 27, 2015 23:11
Show Gist options
  • Save LithionLabs/0c09e8fe18b31eafadee to your computer and use it in GitHub Desktop.
Save LithionLabs/0c09e8fe18b31eafadee to your computer and use it in GitHub Desktop.
Import CSV using fgetcsv() and insert into a MySQL database using PDO.
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=test_db', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e) {
$output = 'Unable to connect to the database';
exit();
}
$clear = "TRUNCATE TABLE test_tbl";
$trunc = $pdo->prepare($clear);
$trunc->execute();
//Path to CSV file. "/var/source_data" is a CIFS mount of a windows share that resides at \\DataSrv02\csv_data on the same network.
define('CSV_PATH', '/var/source_data/');
$csv_file = CSV_PATH . "testData.csv";
$handle = fopen($csv_file, "r");
$row = 1;
for ($i = 0; ($data = fgetcsv($handle, 8000, "|")) !== FALSE; $i++) {
$num = count($data);
$sql = "INSERT INTO test_tbl(company,lastname,firstname,street1,street2,city,state,zipcode,phone) VALUES (:company, :lastname, :firstname, :street1, :street2, :city, :state, :zipcode, :phone)";
$sth = $pdo->prepare($sql);
$sth->bindParam(':company', $data[0]);
$sth->bindParam(':lastname', $data[1]);
$sth->bindParam(':firstname', $data[2]);
$sth->bindParam(':street1', $data[3]);
$sth->bindParam(':street2', $data[4]);
$sth->bindParam(':city', $data[5]);
$sth->bindParam(':state', $data[6]);
$sth->bindParam(':zipcode', $data[7]);
$sth->bindParam(':phone', $data[8]);
$sth->execute();
$sth->closeCursor();
$row++;
}
echo "<p> $num fields and $row total rows inserted into the test_db database.<br /></p>\n";
fclose($handle);
?>
@henriquehorbovyi
Copy link

Good... :D...

@darkcumulus
Copy link

thanks!

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