正如标题中所解释的,我试图通过将csv文件上传到我的php页面来将数据导入到我的表中。 这是我从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>
&#13;
问题是,在提交文件时,只有我文件的最后一行插入到表中。是否有任何修改建议使代码插入csv文件的每一行?
答案 0 :(得分:1)
这应该可以解决您的问题。您没有在循环中执行查询。
<?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;
}
}
}
?>
答案 1 :(得分:0)
下面的CSV文件导入请参见示例:
<?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')";
}
}