Reputation: 599
If I just echo out $reasons after filling in 2 required text fields then it shows the input values for both. But if I try and insert into the database, it only inserts one record and not the second.
function insert_lost_reasons($link){
if (isset($_POST['submit']) && isset($_SESSION['last_id'])) {
$message = "";
foreach($_POST['name'] as $reasons) {
if (empty($reasons)) {
$message = "Please fill in all fields";
}
}
if ($message) {
echo error_message($message);
} else {
foreach($_POST['name'] as $reasons) {
$stmt = $link->prepare("INSERT INTO `lost_time` (`ps_id`, `reason`) SELECT ?, `lost_time_reason_id` FROM `lost_time_reasons` WHERE `lost_time_desc` = ?");
$stmt->bind_param("is", $_SESSION['last_id'], $reasons);
$stmt->execute();
$stmt->close();
unset($_SESSION['token']);
header("location: dash.php");
exit();
}
}
}
}
Upvotes: 1
Views: 67
Reputation: 34914
May be you should write your foreach like this
else {
foreach($_POST['name'] as $reasons) {
$stmt = $link->prepare("INSERT INTO `lost_time` (`ps_id`, `reason`) SELECT ?, `lost_time_reason_id` FROM `lost_time_reasons` WHERE `lost_time_desc` = ?");
$stmt->bind_param("is", $_SESSION['last_id'], $reasons);
$stmt->execute();
}
$stmt->close();
unset($_SESSION['token']);
header("location: dash.php");
exit();
}
You are redirecting in first iteration.
Upvotes: 0
Reputation: 7441
The problem is that you close session and exit on first foreach loop. Wait all loops and then jump with headeer
function.
header("location: dash.php");
exit();
Do this instead:
foreach($_POST['name'] as $reasons) {
//Edit this for your usage
$stmt = $link->prepare("INSERT INTO `lost_time` (`ps_id`, `reason`) SELECT ?, `lost_time_reason_id` FROM `lost_time_reasons` WHERE `lost_time_desc` = ?");
$stmt->bind_param("is", $_SESSION['last_id'], $reasons);
$stmt->execute();
}
$stmt->close();
unset($_SESSION['token']);
header("location: dash.php");
exit();
Upvotes: 1