X
    Categories: MysqlPHP

Import csv file data into mysql database using php

Import csv file data into mysql database using php

Hi, In this tutorial I am going to explain how to Import CSV file data into mysql database.

It’s very simple to do using php. I have added Sample code for reference.

<?php  

//connect to the database 
$connect = mysql_connect("localhost","root",""); 
mysql_select_db("csv",$connect); //select the table 
// 

if (isset($_FILES['csv']['size']) > 0) { 

    //get the csv file 
    $file = $_FILES['csv']['tmp_name']; 
    $handle = fopen($file,"r"); 
    $name = $_FILES['csv']['name'];
    //loop through the csv file and insert into database 
    do { 
        if ($data[0]) { 
		$exist = mysql_num_rows(mysql_query("SELECT contact_number FROM contacts WHERE contact_number = '".addslashes(trim($data[1],'"'))."'"));
		if($exist == 0 ) {
            mysql_query("INSERT INTO contacts (contact_name, contact_number,contact_file) VALUES 
                ( 
                    '".addslashes(trim($data[0],'"'))."', 
                    '".addslashes(trim($data[1],'"'))."',
					'".$name."'
                ) 
            "); 
		}
        } 
    } while ($data = fgetcsv($handle,1000,",","'"));     // 

    //redirect 
	echo '<script> window.loaction.href="../index.php?result=1" </script>';
     die; 

} 

?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<title>Import a CSV File with PHP & MySQL</title> 
</head> 

<body> 

<?php if (isset($_GET['success'])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?> 

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
  Choose your file: <br /> 
  <input name="csv" type="file" id="csv" /> 
  <input type="submit" name="Submit" >
In above example I have table called " Contacts "  and I have my contact number and contact name in CSV file.
fgetcsv PHP function is used to read the csv data's. By using above code I have stored all the records into database. Your CSV data must be like below,
91978456320, Marimuthu
91968574123, 17educations

Comma(,) is the separator.

Thanks!. If you like this article don't forget to share and comment.

 

 

Marimuthu:

View Comments