How to Import CSV Data into MySQL Using PHP?
Introduction :
CSV (Comma Separated Values) is a popular file format used for storing plain text data. It is widely used for importing and exporting data between different programs. In this guide, we will walk you through the steps to import CSV data into a MySQL database using PHP. This tutorial will provide you with a comprehensive understanding of the process, ensuring you can seamlessly manage your data.
Step 1: Create the Database Table :
First, you need to create a table in your MySQL database to store the data from the CSV file. Use the following SQL query to create a members
table :
CREATE TABLE members (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL,
email VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL,
phone VARCHAR(15) COLLATE utf8_unicode_ci NOT NULL,
created DATETIME NOT NULL,
modified DATETIME NOT NULL,
status ENUM('Active', 'Inactive') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Active',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Step 2 : Create the Database Config File
Create a dbconfig.php
file to handle the database connection :
connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Step 3: Create the HTML Form for File Upload
Create an index.php
file where users can upload their CSV files :
Import CSV Data into MySQL Using PHP
Import CSV Data
Step 4: Handle CSV File Import :
Create an importcsvfile.php
file to handle the CSV import logic :
query($prevQuery);
if ($prevResult->num_rows > 0) {
$db->query("UPDATE members SET name = '".$name."', phone = '".$phone."', status = '".$status."', modified = NOW() WHERE email = '".$email."'");
} else {
$db->query("INSERT INTO members (name, email, phone, created, modified, status) VALUES ('".$name."', '".$email."', '".$phone."', NOW(), NOW(), '".$status."')");
}
}
fclose($csvFile);
$qstring = '?status=succ';
} else {
$qstring = '?status=err';
}
} else {
$qstring = '?status=invalid_file';
}
}
header("Location: index.php".$qstring);
?>
Conclusion :
You have successfully learned how to import CSV data into a MySQL database using PHP. This process involves creating a database table, setting up the database configuration, creating a file upload form, and writing the import logic. With this knowledge, you can efficiently manage your data import tasks.