In this php post, I am discussing how to import CSV file into a MySQL database table using PHP.CSV stands for “Comma Separated Values” a file format where data is organized with commas as separators.
Additionally, I will provide instructions on how to perform the same CSV import into MySQL using the command line.
It’s a very common task for every application that has too much database and needs to import into MySQL.
I’ve implemented a two-file approach, with 'index.php'
handling the user interface for uploading CSV files and 'import_csv.php'
responsible for establishing a connection to MySQL, parsing CSV data, and storing it in a MySQL table.
If you are more comfortable watching a video that explains about How To Import CSV File Into MySQL Using PHP, then you should watch this video tutorial.
Normally, We need to import data into the database then we used the following file types.
To import data through CSV file into MySQL Database table. I am doing the following steps to import data from CSV
file into MYSQL
using PHP
Script code.
You can also check another tutorial of Export/Import Data with PHP,
Step 1: Create import_csv.php
and put the below code into this file.
<?php if(isset($_POST["submit"])) { $host="localhost"; // Host name. $db_user="root"; //mysql user $db_password=""; //mysql pass $db='phpDB'; // Database name. //$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error()); //mysql_select_db($db) or die (mysql_error()); $con=mysqli_connect($host,$db_user,$db_password,$db); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } echo $filename=$_FILES["file"]["name"]; $ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,"."))); //we check,file must be have csv extention if($ext=="csv") { $file = fopen($filename, "r"); while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) { $sql = "INSERT into tableName(name,email,address) values('$emapData[0]','$emapData[1]','$emapData[2]')"; mysqli_query($con, $sql); } fclose($file); echo "CSV File has been successfully Imported."; } else { echo "Error: Please Upload only CSV File"; } } ?>
The below code is used for creating an interface to upload CSV file.
Step 2: Create a new index.php file to display the CSV upload form. You need to put the below code into index.php
file.
<form action="import_csv.php" enctype="multipart/form-data" method="post"> <table border="1"> <tbody> <tr> <td colspan="2" align="center"><strong>Import CSV file</strong></td> </tr> <tr> <td align="center">CSV File:</td> <td><input id="file" name="file" type="file"></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="submit"></td> </tr> </tbody> </table> </form>
We can also import a CSV file into a MySQL table using the command line. Let’s open your command line terminal or shell.
You need to run the following command to access your MySQL database, and when prompted, enter your MySQL username and password:
mysql -u username -p
Replace username
with your MySQL username.
Let’s select the database where you want to import the CSV file, if you haven’t created a database, then you need to create one using 'CREATE DATABASE your_database_name'
.
USE your_database_name;
use the LOAD DATA INFILE
statement to import the CSV data. We’ll run the following command to load data.
LOAD DATA LOCAL INFILE 'C:/Users/userName/Downloads/test.csv' INTO TABLE tableName FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
C:/Users/userName/Downloads/test.csv
with the actual path to your CSV file.tableName
with the name of the MySQL table where you want to import the data.FIELDS TERMINATED BY
, ENCLOSED BY
, and LINES TERMINATED BY
options according to your CSV file format.We can also create a single command that ll use username, password and other params in a one command.
mysql -uusername -ppassword --local-infile scrapping -e "LOAD DATA LOCAL INFILE 'CSVname.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"
You can also import file using mysqlimport
command while specifying columns and ignoring lines
mysqlimport --columns='head -n 1 $yourfile' --ignore-lines=1 dbname $yourfile`
Replace yourfile
with the actual name of your CSV file and dbname
with the name of your MySQL database.
This command will import data from the CSV file into the specified database while considering the column headers from the first line and ignoring the first line of data in the CSV file.
Note: The file uses commas as separators and is not delimited by semi-colons.
Exit the MySQL command line interface by typing:
EXIT;
By following the steps outlined in this article, you can easily import CSV data into MySQL using a PHP script. You can also import a CSV file into MySQL via the command line is a powerful and efficient way to manage your database.
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More
View Comments
Thanks for the snippet. It is very helpful. I recommend including/adding the rest of the html page so that folks can just copy, paste and use it "as-is".
thanks, i separated for easy understand.
its working
Where does the csv file live , so that the code can find it in the directory when it runs the import? thx
Right now user can select csv file from any folder but as per your scenario, you can store csv file into root directory of project
it is useful