im trying to store checkbox values inside variable $days
but when i store this value to database it just store the last selected checkbox inside the database... please help me to sort out the code so i can get all selected values
<?php
if (isset($_POST['days'])) {
foreach ($_POST['days'] as $day) {
$days = " " . $day;
}
} else {
$days = "not available";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<tr>
<td>Select Days :</td>
<td>
<input type="checkbox" name="days[]" value="Sunday">Sunday
<input type="checkbox" name="days[]" value="Monday">Monday
<input type="checkbox" name="days[]" value="Tuesday">Tuesday
<input type="checkbox" name="days[]" value="Wednesday">Wednesday
<input type="checkbox" name="days[]" value="Thursday">Thursday
<input type="checkbox" name="days[]" value="Friday">Friday
<input type="checkbox" name="days[]" value="Saturday">Saturday
<input type="checkbox" name="days[]" value="All Days">All Days
</td>
<td></td>
You assign a normal string to $days
and overwrite it on each iteration. You could append to it, by using the .=
operator. ( $days .= ' ' . $day
), but maybe easier is to use implode
:
if (isset($_POST['days'])) {
$days = implode(' ', $_POST['days']);
} else {
$days = "not available";
}
Note there is a small functional difference. implode
will add spaces inbetween the days, while the foreach loop will also put a space at the start.
You overwrite $days
with each iteration of the forech loop. Instead you want to add to it. Most likely this is what you are looking for:
if (isset($_POST['days'])) {
foreach ($_POST['days'] as $day) {
$days .= " " . $day;
}
} else {
$days = "not available";
}
If so, then you can even simplify the code and remove the loop:
if (isset($_POST['days'])) {
$days = implode(" ", $_POST['days']);
} else {
$days = "not available";
}
Use .
to concatate the string
$days .= " " . $day;
You need to make $days as array and then push the values you get from checkbox into array.
$days[] = $day
inside your foreach statement
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.