CSV (Comma-Separated Values) files are widely used for storing and exchanging structured data. Inserting data from a CSV file into a MySQL database is a common requirement for web applications. This article explains how to import multiple records from a CSV file into a MySQL database using PHP.
Step 1: Create a MySQL Database and Table
Before inserting data, we need to create a MySQL table that matches the structure of our CSV file.
Run the following SQL query to create a sample table:
CREATE DATABASE csv_database;
USE csv_database;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
This table has three columns: id, name, and email, where id is an auto-incremented primary key.
Step 2: Insert CSV Data Using PHP
PHP provides built-in functions to read CSV files and insert data into a MySQL database.
Basic PHP Code to Insert CSV Data into MySQL
<?php
// Database connection
$mysqli = new mysqli("localhost", "root", "password", "csv_database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Open CSV file
$file = fopen("data.csv", "r");
// Skip the first row if it contains column headers
fgetcsv($file);
// Read each row and insert it into the database
while (($row = fgetcsv($file, 1000, ",")) !== FALSE) {
$sql = "INSERT INTO users (name, email) VALUES ('$row[0]', '$row[1]')";
$mysqli->query($sql);
}
// Close file and database connection
fclose($file);
$mysqli->close();
echo "Data imported successfully!";
?>
Explanation of the PHP Code:
-
Connects to MySQL using
mysqli. -
Opens the CSV file using
fopen(). -
Reads each row using
fgetcsv(). -
Inserts data into the database using an
INSERT INTOquery. - Closes the file and database connection after completion.
Step 3: Optimize for Large CSV Files
For large CSV files, inserting data row by row can be slow. Instead, we can bulk insert multiple rows in a single query to improve performance.
Optimized PHP Code for Bulk CSV Import
<?php
$mysqli = new mysqli("localhost", "root", "password", "csv_database");
$file = fopen("data.csv", "r");
$values = [];
// Skip the first row if it contains column headers
fgetcsv($file);
while (($row = fgetcsv($file, 1000, ",")) !== FALSE) {
$values[] = "('" . implode("','", array_map('addslashes', $row)) . "')";
}
// Bulk insert query
if (!empty($values)) {
$sql = "INSERT INTO users (name, email) VALUES " . implode(",", $values);
$mysqli->query($sql);
}
fclose($file);
$mysqli->close();
echo "Bulk data imported successfully!";
?>
Why Use Bulk Insert?
- Inserts multiple rows in one query, significantly improving speed.
- Reduces database connection overhead, especially for large datasets.
Step 4: Test the Data Import
After running the PHP script, check if the data has been inserted correctly by running the following SQL query:
SELECT * FROM users;
If everything is set up correctly, you should see the imported data in your database.
Best Practices for CSV Data Import in PHP
✅ Use Bulk Insert: It improves performance when handling large CSV files.
✅ Validate Data Before Importing: Ensure the CSV file has the correct format.
✅ Optimize Database Indexing: Indexing speeds up queries after data insertion.
✅ Handle Special Characters: Use addslashes() to prevent errors.