gpt4 book ai didi

php - 为什么我的数据在MySQL中插入了两次

转载 作者:太空宇宙 更新时间:2023-11-03 11:30:35 24 4
gpt4 key购买 nike

我正在使用 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();
}

?>

最佳答案

查询被执行了两次。

它正在这一行执行:

   mysqli_query($conn, $query2);

然后再次执行,在这一行:

   var_dump(mysqli_query($conn, $query2));

mysqli_query 函数的调用再次执行该函数。该行表示“执行 mysqli_query 函数”,然后输出函数的返回值。

就我们观察到的行为而言,这两行本质上等同于写作:

   $foo2 = mysqli_query($conn, $query2));
$foo2 = mysqli_query($conn, $query2));
var_dump($foo2);

问题代码中使用的模式似乎容易受到 SQL 注入(inject)攻击。使用带有绑定(bind)占位符的准备好的语句。

小鲍比 table https://xkcd.com/327/

OWASP 项目 https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

It’s somewhat shameful that there are so many successful SQL Injection attacks occurring, because it is EXTREMELY simple to avoid SQL Injection vulnerabilities in your code.

关于php - 为什么我的数据在MySQL中插入了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50274048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com