Reputation: 2720
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 ?
Upvotes: 0
Views: 861
Reputation: 468
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;
}
}
}
?>
Upvotes: 1
Reputation: 726
CSV file import below See Example:
<?php
$file = $_FILES['file']['tmp_name'];
//Read the file
$content = file_get_contents($file);
//Split file into lines
$lines = explode("\n", $content);
//Find columns by reading first line
for ($i = 1; $i <= 310; $i++) {
$data = explode("\t", $lines[$i]);
$name = $filesop[0];
$email = $filesop[1];
$sql = "INSERT INTO `xl` (`Name`, `Email`) VALUES ('$name','$email')";
}
}
Upvotes: 0