Sahar Alsadah Sahar Alsadah - 1 month ago 8
HTML Question

Import data from CSV file to Mysql table through php

As explained in the title, I am trying to import data to my table through uploading the csv file to my php page.
This is the code I got from EggSlab



<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}


?>

<html>

<body>

<form name="import" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>

<?php
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];

$sql = "INSERT INTO `xl` (`Name`, `Email`) VALUES ('$name','$email')";

}


if ($conn->query($sql) === TRUE) {
echo "You database has imported successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

?>
</body>

</html>





The problem is that, when submitting the file, only the last row of my file gets inserted to the table. Any suggestion of a modification to make the code insert every row of the csv file ?

Answer

This Should fix your problem. You were not executing the query within the loop.

  		<?php
if(isset($_POST["submit"]))
{
 $file = $_FILES['file']['tmp_name'];
 $handle = fopen($file, "r");
 $c = 0;
 while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
 {
  $name = $filesop[0];
  $email = $filesop[1];
 
  $sql = "INSERT INTO `xl` (`Name`, `Email`) VALUES ('$name','$email')";
  if ($conn->query($sql) === TRUE) {
	 echo "You database has imported successfully";
  } else {
    echo "Error: " . $sql . "<br>" . $conn->error; 
  }
 }
 

 
}

?>