从 for 循环或 foreach 的数组中的 php 中插入多个 sql 语句

Insert Multiple sql statements in php from an array from for loop or foreach

这是我的代码,我必须在插入语句中为每个值插入一个数组

if(isset($_POST['add'])){
    $batch = $_POST['batch'];
    $course = explode(':', $_POST['course']);
    $cid = $course[0];
    $rowCount = count($_POST['branch']);
    $branch = implode(',', $_POST['branch']);
    $semester = $_POST['sem'];
    $day = $_POST['day'];
    $hour = $_POST['hour'];


    for($i=0;$i<$rowCount;$i++){
        $description = $_POST['branch'][$i];
        $sql. = "INSERT INTO batch (batch,bdescription,branch,course,semester,day,hour,user) VALUES ('$batch','$description',$i,'$cid','$semester','$day','$hour','$usnid');";

    }


    if($conn->query($sql)){
        $_SESSION['success'] = 'batch  added successfully';
    }
    else{
        $_SESSION['error'] = $conn->error;
    }
}

请帮忙谢谢

您不能通过一次调用 $conn->query().

来执行多个查询

更改您的查询,使其只是一个 INSERT 语句,在 VALUES 之后有多个值列表。

$sql = "INSERT INTO batch (batch,bdescription,branch,course,semester,day,hour,user) VALUES "
for($i=0;$i<$rowCount;$i++){
    $description = $_POST['branch'][$i];
    $sql. = "('$batch','$description',$i,'$cid','$semester','$day','$hour','$usnid'),";
}
$sql = substr($sql, 0, -1); // remove last comma

您还应该使用 $conn->real_escape_string() 来转义所有输入,以防止 SQL 注入(如果使用准备好的语句来做到这一点会更好,但是很难进行准备mysqli 中带有动态参数的语句)。

Barmar 是正确的,您不能用 query() 执行多个 SQL 语句。有 mysqli_multi_query(),但几乎没有理由使用它。 MySQL 的前工程总监曾经明确告诉我,"there's no reason for multi-query to exist."

您应该使用参数而不是将 $_POST 变量直接复制到您的 SQL 字符串中。这并不难,事实上,它使代码 比摆弄令人困惑的 quotes-within-quotes 和 mysqli_real_escape_string() 等更容易

我不会费心尝试在单个 INSERT 语句中插入多个元组。一个 POST 中可能有多少个分支?最多几十个?不足以使有必要将 INSERT 变成单个语句。因此,只需为准备好的 INSERT 调用 execute(),每行一次。

$sql = "INSERT INTO batch 
        SET batch=?, bdescription=?, branch=?, course=?, semester=?,
            day=?, hour=?, user=?";
$stmt = $conn->prepare($sql) or die($conn->error);

$description = '';
$stmt->bind_param('ssssssss', $batch, $description, $i, $cid, $semester, $day, $hour, $usnid);

for($i=0;$i<$rowCount;$i++){
    $description = $_POST['branch'][$i];
    $stmt->execute() or die($stmt->error);
}

阅读 https://www.php.net/manual/en/mysqli-stmt.bind-param.php 的手册以获取更多代码示例。

这就是我修复代码的方式。我用于循环

    if(isset($_POST['addstd'])){
    $rowCount = count($_POST['student']);

        for($i=0;$i<$rowCount;$i++){
            $stdid = $_POST['student'][$i];
            $course = $_POST['course'][$i];
            $batch = $_POST['batch'][$i];
            $branch = $_POST['branch'][$i];
            //insert students into attendance table

            $sqlsel =  "SELECT year,student_id, student_rollno,firstname,lastname, branch,active, nr FROM student WHERE student.student_id = '$stdid' AND student.branch = '$branch'";
            $querysel = $conn->query($sqlsel) or die($conn->error);
            $rowsel = $querysel->fetch_assoc();
                if($rowsel !== null){
                    $year = $rowsel['year'];
                    $rollno = $rowsel['student_rollno'];
                    $active = $rowsel['active'];        
                    $branch = $rowsel['branch'];
                    $name = $rowsel['firstname'].$rowsel['lastname'];


            $sql = "INSERT IGNORE INTO class (year,regno, rollno,name, programme,coursecode,batch,user,active,count) VALUES ('$year','$stdid','$rollno','$name','$branch','$course','$batch','$usnid','$active','$i');";

            if($conn->query($sql)){
                $_SESSION['success'] = 'Students Added To Batch Successfully';
            }
            else{
                $_SESSION['error'] = $conn->error;
            }
            }
                else{
                    continue;
                }
        }

}
else{
    $_SESSION['error'] = 'Fill up add form first';
}