0

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

2
  • use $days .= " " . $day; Commented Jun 21, 2015 at 11:50
  • thnx for the help :) ..... one dot(.) can make a difference lolzz Commented Jun 21, 2015 at 11:53

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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";
}  

Comments

0

Use . to concatate the string

$days .= " " . $day;

Comments

-1

You need to make $days as array and then push the values you get from checkbox into array.

$days[] = $day

inside your foreach statement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.