简体   繁体   English

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

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

This is my code I have to insert an array each value in the insert statement 这是我的代码我必须在insert语句中插入每个值的数组

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;
    }
}

Please help thanks 请帮助谢谢

You can't execute multiple queries with a single call to $conn->query() . 只需调用$conn->query()就无法执行多个查询。

Change your query so it's just a single INSERT statement with multiple lists of values after VALUES . 更改您的查询,因此它只是一个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

You should also use $conn->real_escape_string() to escape all the inputs, to protect against SQL injection (it would be even better to do that with a prepared statement, but it's difficult to make a prepared statement in mysqli with dynamic parameters). 您还应该使用$conn->real_escape_string()来转义所有输入,以防止SQL注入(使用$conn->real_escape_string()准备语句执行此操作会更好,但很难在mysqli使用动态参数进行预处理语句) 。

Barmar is correct, you can't execute multiple SQL statements with query() . Barmar是正确的,你不能用query()执行多个SQL语句。 There's mysqli_multi_query() , but there's hardly ever a justification for using that. mysqli_multi_query() ,但几乎没有理由使用它。 The former Engineering Director for MySQL once told me unequivocally, "there's no reason for multi-query to exist." MySQL的前任工程总监曾毫不含糊地告诉我,“没有理由存在多查询。”

You should use parameters instead of copying $_POST variables directly into your SQL strings. 您应该使用参数而不是将$ _POST变量直接复制到SQL字符串中。 It's not hard, in fact it makes code easier than fiddling with confusing quotes-within-quotes and mysqli_real_escape_string() and so on. 这并不难,事实上它使代码比在引号和mysqli_real_escape_string()等混乱的引号更容易

I wouldn't bother with trying to insert multiple tuples in a single INSERT statement. 我不打算尝试在单个INSERT语句中插入多个元组。 How many branches can possibly be in a single POST? 一个POST中可能有多少个分支? A few dozen at most? 最多几打? Not enough to make it necessary to make the INSERT into a single statement. 不足以使INSERT成为单个语句。 So just call execute() for a prepared INSERT, once for each row. 因此,只需为准备好的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);
}

Read the manual for https://www.php.net/manual/en/mysqli-stmt.bind-param.php for more code examples. 有关更多代码示例, 阅读https://www.php.net/manual/en/mysqli-stmt.bind-param.php的手册。

This is how I Fixed My Code. 这就是我修复我的代码的方法。 I Used for loop 我用于循环

    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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM