Monday, 18 April 2016

Upload CSV and Insert Data into Mysql Using PHP

In this post I will show you how to insert CSV file data into Mysql Database table using PHP Language. In this tutorial I will explain database table, upload csv file, get data from csv file and after insert that data into database. If you want to insert large amount of data which is store under CSV file and you want insert into to Mysql database then at that time this type of concept you can use. For this I have use simple fgetcsv() function for fetch all data from CSV file and after that I have run insert query for insert data into table.

Source Code

 $connect = mysqli_connect("localhost", "root", "", "test_db");  
           $filename = explode('.',$_FILES['file']['name']);  
           if($filename[1] == 'csv')  
                $handle = fopen($_FILES['file']['tmp_name'], "r");  
                while($data = fgetcsv($handle))  
                     $item1 = mysqli_real_escape_string($connect, $data[0]);  
                     $item2 = mysqli_real_escape_string($connect, $data[1]);  
                     $sql="INSERT into tbl_excel(excel_name, excel_email) values('$item1','$item2')";  
                     mysqli_query($connect, $sql);  
                print "Import done";  
 <!DOCTYPE html>  
           <title>Webslesson Tutorial</title>       
           <form method='POST' enctype='multipart/form-data'>  
                <div align="center">  
                     <p>Upload CSV: <input type='file' name='file' /></p>  
                     <p><input type='submit' name='submit' value='Import' /></p>  

1 comment: