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 ?
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; } } } ?>
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')";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.