Home » Php » php – Foreach loop ONLY adds last value in array to table

php – Foreach loop ONLY adds last value in array to table

Posted by: admin February 25, 2020 Leave a comment

Questions:

Forgive me for I am relatively new to PHP and MYSQL and I believe this maybe be an easy question to answer(or maybe not, i’m not sure).
Here is my HTML form of checkboxes

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

Fairly simple. Then I have this PHP in process.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);

I am attempting to make a foreach loop with my checkboxes and then insert each checkbox value into a new row in my MYSQL table. However when I run this PHP, it only inserts the last checked checkbox value into the MYSQLtable and does not insert all. How can I loop it so it will insert all checked values into my table. Thank you for the help!

How to&Answers:

What you did is just replacing the string $sql, but your execution of actually inserting into database is written after loop, that’s why it’s only inserting the last checkbox.

Try this:

$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);

Also, please note that the way you are inserting(looping) is very slow because it’s executing quite a number of queries. You should use batch insert instead.

Warning: As mentioned by Darman in the comment

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!

Answer:

You can also take this opportunity to correct the SQL injection vulnerability.

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

Answer:

when you’re setting :

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

it is only a string bieng set to $sql varaible where

mysqli_query($conn,$sql)

is which executing the SQL query to insert the data into the table so move

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