假设我在.csv文件中有3行,有3列。在这种情况下,我需要导入完全相同的文件3次,以便将.csv文件中的所有数据完全插入到我的SQL数据库中。我以为!feof($file)
应该确保循环到文件末尾?
if (isset($_POST['submitI'])){
$filename = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while (!feof($file)){
$getData = fgetcsv($file, '0');
$sql = "SELECT * FROM murid WHERE No_Sek_Murid = '".$getData[0]."'";
$result = mysqli_query($conn, $sql);
if(empty($getData[0] || $getData[1] || $getData[2])){
$errorForm = "Sila isikan semua medan dalam fail!";
echo "<script type='text/javascript'>alert('$errorForm');</script>";
echo "<script> location.href='../main.php'; </script>";
exit();
}
if(mysqli_num_rows($result) === 0){
$sqlMurid = "INSERT INTO murid (No_Sek_Murid, Nama_Murid, Kelas_Murid) VALUES ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."')";
$sqlKelab = "INSERT INTO kelab (Kod_Kelab, No_Sek_Murid, ID_Pengguna) VALUES ('{$_SESSION['kodKelab']}', '".$getData[0]."', '{$_SESSION['username']}')";
mysqli_query($conn, $sqlMurid);
mysqli_query($conn, $sqlKelab);
$success = "Berjaya menambah rekod ke dalam pangkalan data!";
echo "<script type='text/javascript'>alert('$success');</script>";
echo "<script> location.href='../main.php'; </script>";
exit();
}
} fclose($file);
} else {
$errorfile = "Operasi import gagal!";
echo "<script type='text/javascript'>alert('$errorfile');</script>";
echo "<script> location.href='../main.php'; </script>";
exit();
}
}
答案 0 :(得分:0)
不必要地使用exit()。你也将多个参数传递给empty()函数,这似乎是不正确的。您可以在没有退出功能的情况下运行代码,如下所示:
if (isset($_POST['submitI'])){
$filename = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while (!feof($file)){
$getData = fgetcsv($file, '0');
$sql = "SELECT * FROM murid WHERE No_Sek_Murid = '".$getData[0]."'";
$result = mysqli_query($conn, $sql);
if(empty($getData[0]) || empty($getData[1]) || empty($getData[2])){
$errorForm = "Sila isikan semua medan dalam fail!";
echo "<script type='text/javascript'>alert('$errorForm');</script>";
echo "<script> location.href='../main.php'; </script>";
} elseif(mysqli_num_rows($result) === 0){
$sqlMurid = "INSERT INTO murid (No_Sek_Murid, Nama_Murid, Kelas_Murid) VALUES ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."')";
$sqlKelab = "INSERT INTO kelab (Kod_Kelab, No_Sek_Murid, ID_Pengguna) VALUES ('{$_SESSION['kodKelab']}', '".$getData[0]."', '{$_SESSION['username']}')";
mysqli_query($conn, $sqlMurid);
mysqli_query($conn, $sqlKelab);
$success = "Berjaya menambah rekod ke dalam pangkalan data!";
echo "<script type='text/javascript'>alert('$success');</script>";
echo "<script> location.href='../main.php'; </script>";
}
} fclose($file);
} else {
$errorfile = "Operasi import gagal!";
echo "<script type='text/javascript'>alert('$errorfile');</script>";
echo "<script> location.href='../main.php'; </script>";
}