我正在使用PHP和MySQL数据库来完成我的学校项目。当我尝试在数据库中导入数据时遇到问题。在第一个表(murid表)中它完美地工作,但在第二个表(pendaftaran表)中,它似乎导入了两次。这是我的PHP代码。我想知道为什么我的数据在pendaftaran表中插入两次?
<?php
session_start();
$username = $_SESSION['username'];
$conn = mysqli_connect('localhost','root','','darksith');
if(!$conn)
{
echo 'Not connected';
}
if (isset($_POST['importbutton'])) {
$namaFail = $_FILES['file']['tmp_name'];
if ($_FILES['file']['size'] > 0) {
$fail = fopen($namaFail, 'r');
while (!feof($fail)) {
$data = fgetcsv($fail, '0');
$query = "SELECT * FROM murid WHERE No_Sekolah_Murid = '".$data[0]."'";
$result = mysqli_query($conn, $query);
if (empty($data[0] || $data[1] || $data[2] || $data[3])) {
echo "<script>
window.alert('Sila isikan semua medan dalam fail!');
window.location = '';
</script>";
//exit();
} else {
if (mysqli_num_rows($result) === 0) {
$query1 = "INSERT INTO murid(No_Sekolah_Murid, Nama_Murid, Kelas, Tarikh_Daftar) VALUES('".$data[0]."', '".$data[1]."', '".$data[2]."',NOW())";
$query2 = "INSERT INTO pendaftaran(ID_Pendaftaran, ID_Pengguna, No_Sekolah_Murid, Kod_Pertubuhan) VALUES('', '$username', '".$data[0]."', '".$data[3]."')";
mysqli_query($conn, $query1);
var_dump(mysqli_query($conn, $query1));
mysqli_query($conn, $query2);
var_dump(mysqli_query($conn, $query2));
// echo "<script>
// window.alert('Rekod berjaya ditambahkan!');
// window.location = 'import.html';
// </script>";
} else {
"<script>
window.alert('Rekod gagal ditambahkan!');
window.location = 'import.html';
</script>";
}
}
} fclose($fail);
}
} else {
echo "<script>
window.alert('Import gagal. Sila cuba sekali lagi!');
window.location = 'import.html';
</script>";
exit();
}
?>
答案 0 :(得分:0)
更改下面提到的代码:
mysqli_query($conn, $query2);
var_dump(mysqli_query($conn, $query2));
到
$sqlExecRes = mysqli_query($conn, $query2);
var_dump($sqlExecRes);