PHP (Core & Framework)

How to import Records from CSV file using PHP and MySql

In this article, I will discuss how you can export data from and to CSV files using PHP and MySQL.

This is a very useful and important for users because you can add multiple records in one go.

When the add button is clicked, the temporary file name will be stored in memory and using the `while` loop the data is saved in $getData variable. Once the process has been completed, the data is sorted column wise and then finally inserted in the `myrecords` table (according to the given code) .

Note that `fgetcsv()` from the open file, checking for CSV fields and `fopen()` opens a file or a URL. 

<?php session_start();?>

<!DOCTYPE html>

<html>
<head>
	<title>User Detail Form</title>
</head>
<body>
	<h1><u>IMPORT RECORD</u></h1><br><br>
	<?php
	include("connectins.php");

if(isset($_POST['submit']))
{
	$filename=$_FILES["file"]["tmp_name"];    
     if($_FILES["file"]["size"] > 0)
     {
        $file = fopen($filename, "r");
        $n=0;
          while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
           {
           	
            $sql = "INSERT into myrecords (user_id,title,startdate,enddate,postdate,type) 
                   values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$getData[4]."','".$getData[5]."')";
                  
                   $result = mysqli_query($conn, $sql);
                   $n=$n+1;
                   echo mysqli_error($conn);
                  
            
           }
           echo "record imported successfully ! ";
            
      
           fclose($file);  
     }
  }   

	

else
{
?>	
	<form method="post" name="myform" action="" enctype="multipart/form-data">
		
		Select File:<input type="file" name="file" id="file"><br>
		
		
		<input type="submit" name="submit" value="Add">
	</form>

<?php
}
?>
</body>
</html>

This is a simple example you can. Add more complex logic and validations as per your requirements.

Posted By: Rhythm Arya

Comment here

14 + = 17