Import data from CSV file to MySQL database in PHP

0
86
PHP

This tutorial explains how to import data from external CSV file and insert the data into MySQL database table in PHP

Create a PHP file upload_csv.php

   <form method="post" action="upload_csv.php" enctype="multipart/form-data">
  <input name="file" id="filesToUpload" type="file" multiple="" />
  <input type="submit" value="Upload" class="btn btn-success" />
</form>

<?php

 if(isset($_FILES["file"])){
$connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($connect->connect_error)
		die("Unable to Connect to ".DB_HOST." : ".$connect->connect_error);
		$filename=$_FILES["file"]["tmp_name"];		
		 if($_FILES["file"]["size"] > 0)
		 {
                     
		  	$file = fopen($filename, "r");
	        while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
	         {
                     $name=$getData[1];
                     $email=$getData[2];
                     $mobile=$getData[3];
                    $insert_query="insert into users (name, email, mobile) values ('$name', '$email', '$mobile')";                                $connect->query($insert_query);
                    
	         }
		fclose($file);		
             
                 
                 
		 }
	}	 
?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here