Import CSV Data Into MySQL Using PHP
In this tutorial, I will write about how to import csv file data into mysql database using php. I will send csv file using html input type file to perform php code in the file. There are many different ways to import csv file like fgetcsv(), php excel library. Here I am using fgetcsv to get coma separated values.
Note: Mysql database table columns and csv file columns must be equal for php import csv.
HTML Form to Import CSV into MySQL
First step is to create an html form and write an input tag to upload csv file. Then write a button for submitting html form to php read csv and php import csv into mysql database table. When a user click on submit button php code will read the file and mysql insert query will insert the csv data into mysql table using a while loop. I am using bulma css for the designing of this html form.
Import CSV File Using PHP
Create Table in MySQL Database
Next I will create a table in mysql database to save imported data.Below is its query to create table in mysql database.
CREATE TABLE `person` ( `id` int(11) NOT NULL, `firstname` varchar(100) NOT NULL, `lastname` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `address` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `person` ADD PRIMARY KEY (`id`); ALTER TABLE `person` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
CREATE TABLE `person` ( `id` int(11) NOT NULL, `firstname` varchar(100) NOT NULL, `lastname` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `address` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `person` ADD PRIMARY KEY (`id`); ALTER TABLE `person` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
PHP Code to Import CSV Data to MySQL
In php code first of all store the file name within a varibale. The use an if statement to check the csv file size is greater than zero. Now read csv file using fopen() function. Using a while loop use fgetcsv() function in the while loop to parse the csv file and then write mysql insert query to import csv data into mysql.
Below is the code of php import csv.
Config.php File Code
Now if you will complete all above steps csv data will be imported into mysql database table. After importing csv data lets display the data in html table usig mysql select query which is used to fetch data from database table.
HTML Table to Fetch Imported Data From MySQL
In this table first of all write mysql select query and execute the query. Then check if mysql table has records to display in html table using if statement in php code. If mysql table rows are greater than zero then display data in html table.
Write this code after the closing tag of html form.
0) {
?>
ID | First Name | Last Name | Address | |
---|---|---|---|---|
Below is the screenshot of html table. This table is the output of import csv into mysql table in php.
Click Here To Download Source Code
php import csv output |
No comments:
Post a Comment