如何更改我的 PHP foreach looped SQL-Insert into a prepared-statement SQL loop?

How to change my PHP foreach looped SQL-Insert into a prepared-statement SQL loop?

我有一个循环查询,用于向 MySQL 数据库中插入数据,它可以完美地完成我需要它做的事情,因为它需要数组中的所有用户输入,然后循环它们并将每个输入到他们在数据库中的行。

$sql_insert_race_history = "INSERT INTO inf_race_history 
                                    (`inf_id`,`race_history`, `results`) 
                            VALUES ";

if ($vracehistory != '') {
    foreach ($vracehistory as $kay => $value) {
        // $sql .= '' | $sql = $sql . '';
        $sql_insert_race_history .= "('$inserted_id','{$value}','{$results[$kay]}'),";
    }
} else {
    $vracehistory = '';
}
// remove last `,` into query;
$sql_insert_race_history = rtrim($sql_insert_race_history, ',');
$countRow = count($_POST['racehist']);
//INSERT INTO THE DATABASE VIA QUERY
$results_racehistory = mysqli_query($vconn, $sql_insert_race_history);

这段代码可以正常工作并根据需要插入所有内容但是我被告知它容易受到 SQL 注入攻击,所以我一直试图通过在每个版本中使用准备好的语句来防止这种情况我只尝试到目前为止循环不起作用,它只上传数组中的最后一项

$stmtrace = $conn->prepare("INSERT INTO inf_race_history 
                                   (`inf_id`,`race_history`, `results`) 
                            VALUES (?,?,?)");
if ($vracehistory != '') {
    foreach ($vracehistory as $kay => $value) {
        $stmtrace->bind_param("sss", $inserted_id,$value,$results[$kay]);
    }
} else {
    $vracehistory = '';
}
// remove last `,` into query;
$sql_insert_race_history = rtrim($stmtrace, ',');
$countRow = count($_POST['racehist']);
//INSERT INTO THE DATABASE VIA QUERY
$stmtrace->execute();

我认为这可能与将 foreach 循环中的 .= 更改为仅 ->bind_param 有关,因为这可能会剥夺循环它的机会?我不太确定,而且我将如何回应我尝试回应 $stmtrace 虽然它说 method _tostring is not implemented

您应该将 execute() 放在循环中。

在foreach循环外绑定参数,在foreach循环内赋值时赋值并执行查询。例如

$stmtrace->bind_param("sss", $insertId, $insertValue, $insertKey);
foreach ($vracehistory as $kay => $value) {
    $insertId = inserted_id;
    $insertValue = $value;
    $insertKey = $kay;
    $stmtrace->execute();
}

另外注意,如果绑定整数,bind_param方法的值应该是'i'.

foreach ($vracehistory as $kay => $value) {
    $stmtrace->bind_param("sss", $inserted_id, $value, $results[$kay]);
    $stmtrace->execute();
}