我在多个数据插入代码中有一个问题,它无法正常工作,我不知道为什么有人可以帮助我 我会为您提供代码
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')";
}
答案 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();
}