Foreach 循环仅将数组中的最后一个值添加到 table

Foreach loop ONLY adds last value in array to table

请原谅我,因为我对 PHP 和 MYSQL 比较陌生,我相信这可能是一个容易回答的问题(也可能不是,我不确定)。 这是我的 HTML 形式的复选框

<form method="post" action="process.php">
<input type="checkbox" name="athlete[]" value="1">athlete 1
<br>
<input type="checkbox" name="athlete[]" value="2">athlete 2
<br>
<input type="checkbox" name="athlete[]" value="3">athlete 3
<br><br>
<input type="submit" value="Submit">
</form>

相当简单。然后我在 process.php:

中有这个 PHP
$checkboxes = isset($_POST['athlete']) ? $_POST['athlete'] : array();
foreach($checkboxes as $value) {
    $sql = "INSERT INTO draftPick(user_id, athlete_id)VALUES('77', '$value' )";
}

if(mysqli_query($conn,$sql)) {

    echo 'Data added sucessfully';
}
else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);

我试图用我的复选框创建一个 foreach 循环,然后将每个复选框值插入到我的 MYSQL table. 中的一个新行但是当我 运行 这个 PHP 时,它 将最后选中的复选框值插入 MYSQLtable 而不是全部插入。我如何循环它以便将 所有 检查的值插入我的 table。感谢您的帮助!

你只是替换字符串$sql,但是你实际插入数据库的执行是在循环之后写的,所以它只插入最后一个复选框。

试试这个:

$checkboxes = isset($_POST['athlete']) ? $_POST['athlete'] : array();
foreach($checkboxes as $value) {
    $sql = "INSERT INTO draftPick(user_id, athlete_id)VALUES('77', '$value' )";

    if(mysqli_query($conn,$sql)) {
        echo 'Data added sucessfully';
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

}

mysqli_close($conn);

另外,请注意您插入(循环)的方式非常慢,因为它执行了相当多的查询。您应该改用 batch insert

警告:正如 Darman 在评论中提到的

You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!

当您设置时:

 $sql = "INSERT INTO draftPick(user_id, athlete_id)VALUES('77', '$value' )";

它只是一个设置为 $sql 变量的字符串 bieng,其中

mysqli_query($conn,$sql)

是执行 SQL 查询将数据插入 table 所以移动

foreach($checkboxes as $value) {
  $sql = "INSERT INTO draftPick(user_id, athlete_id)VALUES('77', '$value' )";
  mysqli_query($conn,$sql);
}

您也可以借此机会修复SQL注入漏洞。

$stmt = $conn->prepare('INSERT INTO draftPick (user_id, athlete_id) VALUES ('77', ? )');
$stmt->bind_param('i', $value);
foreach($checkboxes as $value) {
    $stmt->execute();
}