PHP Import CSV Into MYSQL Database (Simple Example)

Welcome to a quick tutorial on how to import CSV files into an MYSQL database in PHP. Want to allow administrators to upload their own set of data into the database? Yes, it is actually pretty easy to do in PHP – Let us walk through an example in this guide, read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

 

TABLE OF CONTENTS

 

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

QUICK NOTES

  • Create a test database and import 1a-users.sql.
  • Change the database settings in 3-import.php to your own.
  • Access 2-upload.html in the browser and upload 1b-users.csv.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

IMPORT CSV INTO MYSQL DATABASE

All right, let us now get into the example of how to import a CSV file in PHP and MySQL.

 

STEP 1) DUMMY DATABASE & CSV

1A) USERS TABLE

1a-users.sql
CREATE TABLE `users` (
  `user_id` bigint(20) NOT NULL,
  `user_email` varchar(255) NOT NULL,
  `user_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `user_email` (`user_email`),
  ADD KEY `user_name` (`user_name`);

ALTER TABLE `users`
  MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT;

For this example, we will be working with this dummy users table. Very straightforward with only 3 fields –

  • user_id ID, primary key.
  • user_email The user’s email.
  • user_name The user’s name.

 

1B) USERS CSV

jane@doe.com Jane Doe
joe@doe.com Joe Doe
john@doe.com John Doe

That’s right. Just a whole bunch of user emails and names.

 

 

STEP 2) CSV FILE UPLOAD

2-upload.html
<form action="3-import.php" method="post" enctype="multipart/form-data">
  <input type="file" name="upcsv" accept=".csv" required>
  <input type="submit" value="Upload">
</form>

Next, we have a simple HTML file upload form that only accepts CSV files.

 

STEP 3) PHP IMPORT CSV INTO MYSQL

3-import.php
<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbHost = "localhost";
$dbName = "test";
$dbChar = "utf8";
$dbUser = "root";
$dbPass = "";
try {
  $pdo = new PDO(
    "mysql:host=".$dbHost.";dbname=".$dbName.";charset=".$dbChar,
    $dbUser, $dbPass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
  );
} catch (Exception $ex) { exit($ex->getMessage()); }
 
// (B) READ UPLOADED CSV
$fh = fopen($_FILES["upcsv"]["tmp_name"], "r");
if ($fh === false) { exit("Failed to open uploaded CSV file"); }
 
// (C) IMPORT ROW BY ROW
while (($row = fgetcsv($fh)) !== false) {
  try {
    // print_r($row);
    $stmt = $pdo->prepare("INSERT INTO `users` (`user_email`, `user_name`) VALUES (?,?)");
    $stmt->execute([$row[0], $row[1]]);
  } catch (Exception $ex) { echo $ex->getmessage(); }
}
fclose($fh);
echo "DONE.";

Finally, the PHP script to import the uploaded CSV file.

  1. Connect to the database. Remember to change the settings to your own.
  2. Try to open the uploaded CSV file.
  3. Read and import the CSV file into the database row-by-row.

The end.

 

 

EXTRA) RECOMMENDATIONS & TIPS

<?php
// (A) SET TIME LIMIT (SECONDS)
set_time_limit(300);

// (B) DATA CHECK
while (($row = fgetcsv($fh)) !== false) {
  if (!filter_var($row[0], FILTER_VALIDATE_EMAIL)) {
    echo "INVALID EMAIL FORMAT - " . $row[1];
    continue;
  }
}

The above example will work well enough, but always expect things to go wrong. Here are a few common “possible errors” and tips on handling them:

  • PHP scripts will timeout when importing a large CSV file, a simple “fix” is to set a longer timeout with set_time_limit(SECONDS). The advanced way is to run the import script in the background – See the links below.
  • Users will sometimes mess up the CSV data. For example, by swapping the email/name columns and leaving empty rows. As above, check every cell before you import them. Make sure it is a valid email, not an empty cell, etc…
  • Then, there is also the problem of impatient users who will reload and import again – Ending up with duplicate entries. Impose your own unique keys in the database to prevent duplicates.

 

 

EXTRA BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

PHP Import CSV Into MYSQL (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “PHP Import CSV Into MYSQL Database (Simple Example)”

Leave a Comment

Your email address will not be published. Required fields are marked *