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

时间:2019-06-13 01:21:31

标签: php sql-injection

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

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

请帮助谢谢

3 个答案:

答案 0 :(得分:0)

您无法通过一次调用$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注入(最好使用一条预处理语句来做到这一点,但是很难在{{1}中创建一条预处理语句}和动态参数。

答案 1 :(得分:0)

Barmar是正确的,您不能使用query()执行多个SQL语句。有mysqli_multi_query(),但几乎没有理由使用它。 MySQL的前工程总监曾经明确地告诉我,“没有理由存在多重查询。”

您应该使用参数,而不是将$ _POST变量直接复制到SQL字符串中。这并不难,实际上,它使代码更容易,而不是使引号内的引号和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的手册。

答案 2 :(得分:0)

这就是我固定代码的方式。我用于循环

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