PHP中的多重插入查询错误不起作用

时间:2019-05-02 21:22:11

标签: php mysql sql mysqli

我在多个数据插入代码中有一个问题,它无法正常工作,我不知道为什么有人可以帮助我 我会为您提供代码

if(isset($_POST['save']))
    {
        $attendanceStudentName = $_POST['name'];
        $attendanceStudentRollNo = $_POST['rollNumber'];
        $attendanceClass = $_POST['className'];
        $attendanceStatus = $_POST['attendance'];

        $query = "";
        for($count = 0; $count<count($attendanceStudentName); $count++)
        {
            $attendanceStudentName_clean = mysqli_real_escape_string($conn, $attendanceStudentName[$count]);
            $attendanceStudentRollNo_clean = mysqli_real_escape_string($conn, $attendanceStudentRollNo[$count]);
            $attendanceClass_clean = mysqli_real_escape_string($conn, $attendanceClass[$count]);
            $attendanceStatus_clean = mysqli_real_escape_string($conn, $attendanceStatus[$count]);

            $query .= "insert into attendance(id, attendanceStudentName, attendanceStudentRollNo, attendanceClass, attendanceStatus)
            VALUES(NULL, '$attendanceStudentName_clean', '$attendanceStudentRollNo_clean', '$attendanceClass_clean', '$attendanceStatus_clean')";
        }

1 个答案:

答案 0 :(得分:0)

您不能像这样将多个查询串联在一起(即使您使用mysqli_multi_query(),也需要用;分隔查询,而您没有这样做)。

您可以编写一个INSERT之后的具有多个值列表的VALUES查询:

INSERT INTO tablename (col, col, ...) VALUES (val, val, ...), (val, val, ...), ...

所以这样写:

$query = "insert into attendance(id, attendanceStudentName, attendanceStudentRollNo, attendanceClass, attendanceStatus) VALUES ";
$values_array = [];
for($count = 0; $count<count($attendanceStudentName); $count++)
{
    $attendanceStudentName_clean = mysqli_real_escape_string($conn, $attendanceStudentName[$count]);
    $attendanceStudentRollNo_clean = mysqli_real_escape_string($conn, $attendanceStudentRollNo[$count]);
    $attendanceClass_clean = mysqli_real_escape_string($conn, $attendanceClass[$count]);
    $attendanceStatus_clean = mysqli_real_escape_string($conn, $attendanceStatus[$count]);

    $values_array[] = "(NULL, '$attendanceStudentName_clean', '$attendanceStudentRollNo_clean', '$attendanceClass_clean', '$attendanceStatus_clean')";
}
$query .= implode(', ', $values_array);

另一种更好地避免SQL注入的方法是使用准备好的语句,然后在循环中执行它。

$query = "insert into attendance(id, attendanceStudentName, attendanceStudentRollNo, attendanceClass, attendanceStatus) 
        VALUES (NULL, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $name, $rollno, $class, $status);
for($count = 0; $count<count($attendanceStudentName); $count++)
{
    $name = $attendanceStudentName[$count];
    $rollno = $attendanceStudentRollNo[$count];
    $class = $attendanceClass[$count];
    $status = $attendanceStatus[$count];

    $stmt->execute();
}