I’m trying to do a bulk-update from a formular and validate the input before posting it to database. But I must do something wrong, probably with the header location link in wrong place beacause it only validates the first id and don’t care about the other ones.
if ($_SERVER["REQUEST_METHOD"] == "POST" AND $_POST["type"] == "bulk-update") {
$ids = explode(',', $_GET['ids']);
foreach ($ids as $id) {
$post_data = [
'team' => $_POST['team_' . $id],
'player1' => $_POST['player1_' . $id],
'email' => $_POST['email_' . $id],
];
if (empty($post_data["team"])) {
$teamErr = "Fyll i namnet på laget";
} else {
$team = test_input($post_data["team"]);
}
if (empty($post_data["player1"])) {
$player_1Err = "Fyll i namn på spelare 1";
} else {
$player_1 = test_input($post_data["player1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zåäöÅÄÖ -]+$/i",$player_1)) {
$player_1Err = "Bara bokstäver och mellanslag är giltiga";
}
}
if (empty($post_data["email"])) {
$emailErr = "Fyll i en e-postadress";
} else {
$email = test_input($post_data["email"]);
$email = strtolower($email);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Detta är inte en giltig e-postadress";
}
}
if ($teamErr == '' && $player_1Err == "" && $emailErr == "") {
// Update the teams in the database
$stmt = $db->prepare('UPDATE anmalningar SET team = ?, player1 = ?, email = ? WHERE id = ?');
$stmt->execute([ $team, $player_1, $email, $id ]);
// Redirect and output message
header("Location: /tavlingar/skapa_csv.php?bulk-upd&ids={$_GET['ids']}");
exit();
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = ucwords($data);
return $data;
}
2
Answers
I had to put the redirect outside the loop as mentioned above here. But with just that the problem was still there. It just validated and posted the the first loop to the database. So I had to change the redirect code to this outside the loop.
As brombeer mentioned in a comment to your original post, you are redirecting away from the page after the first database update.
You need to do the redirect after all of the loops have run.
Below is your original code, but I have moved the redirect to take place after the foreach loop completes its iterations.