Benson O Thomas
Benson O Thomas

Reputation: 41

How can I retain checkboxes checked state after page submit and reload?

I have a table called property_amenities which has columns; amenity_id and amenity_name whose values are populated on a form as checkboxes. Upon form submission, the checked values are inserted into property_listings table on column property_amenities as an array.

    <?php
      $db_host="localhost";
      $db_name="cl43-realv3";
      $db_user="root";
      $db_pass="";

        try
        {
          $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
          $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e)
        {
          $e->getMessage();
        }

        if (isset($_POST['list_property'])) {
          if (isset($_POST['property_amenities'])) { 
            $property_amenities = implode(",",$_POST['property_amenities']);
          }else{ $property_amenities = "";}
        }
     ?>
      <!DOCTYPE html>
      <html>
      <head>
        <title></title>
      </head>
      <body>
          <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
         <div class="row clearfix">
          <div class="col-lg-12 col-md-6 col-sm-12">  
        <?php
          $stm = $DB_con->prepare("SELECT * FROM property_amenities");
          $stm->execute(array(
          ));

          while ($row = $stm->fetch()){
            $amenity_id = $row['amenity_id'];
            $amenity_name = $row['amenity_name']; 
            $List[] ="<label class=checkbox> <input type=checkbox name='property_amenities[]' value='$amenity_name'> $amenity_name</label>";
          }
          $allamenities = $stm->rowCount();

          $how_many_chunks = $allamenities/3;

          $roster_chunks = array_chunk($List, round($how_many_chunks), true);
          ?>

            <label>Property Amenities</label></small>

        <?php
          foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
            echo "<div class='col-lg-3 col-md-6 col-sm-12'>";
            echo join($roster_chunk_value);
            echo '</div>';
          }
        ?>                                

          </div> 
         </div><!-- end row -->
        <button type="submit" class="btn btn-primary" name="list_property" >SUBMIT PROPERTY</button>
        </form>
    </body>
    </html>

The above code works fine. The only problem is that when I submit the form and the page reloads all the checkboxes of property_amenities are unchecked, what I want is the checkboxes that were checked before page submit to be checked.

How can I achieve this?

Here is the property_amenities table

--
-- Table structure for table `property_amenities`
--

CREATE TABLE `property_amenities` (
  `amenity_id` int(11) NOT NULL,
  `amenity_name` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `property_amenities`
--

INSERT INTO `property_amenities` (`amenity_id`, `amenity_name`) VALUES
(1, 'Outdoor Balcony'),
(2, 'Outdoor Yard Access'),
(3, 'Large Windows/Natural Light'),
(4, 'Closet Space'),
(5, 'Storage Space'),
(6, 'Laundry in Unit'),
(7, 'Parking Garage'),
(8, 'Ample Parking'),
(9, 'Stainless Steel Appliances'),
(10, 'Open Floor Plan'),
(11, 'Newly Renovated'),
(12, 'Close to Social Amenities'),
(13, 'Swimming Pool'),
(14, 'Courtyard'),
(15, 'Electric Fence'),
(16, 'Intercom'),
(17, 'Patio'),
(18, 'Internet'),
(19, 'Guest Quarters'),
(20, 'Gym / Workout Room'),
(21, 'Kitchenette'),
(22, 'Day And Night Guards'),
(23, 'Borehole'),
(24, 'Street Lights'),
(25, '3 Phase Power'),
(26, 'Dhobi Area'),
(27, 'Wheelchair Access '),
(28, 'Generator');

Upvotes: 0

Views: 494

Answers (2)

Angel Politis
Angel Politis

Reputation: 11313

Simply check in your database which checkboxes were checked and include the checked attribute to those who were when you echo the checkboxes:

$checked = (condition) ? "checked" : "";

$List[] = "<label class=checkbox>
              <input type=checkbox name='...' value='$amenity_name' $checked/>
              $amenity_name
           </label>";

Edit:

(In response to the comment)

Since the value of each checkbox is the name of the amenity, you can easily find the check checkboxes by using the $_POST['property_amenities'] array you get on submission of the form:

  1. First, create an empty array for the checked amenities ($amenities_checked).
  2. Then, check if there are any checked amenities using isset($_POST["property_amenities"]). If so, update the value of the array created above.
  3. Inside your while loop, check if the name of the amenity is in that array.

Code for steps 1 & 2:

# Initialise an array to store the amenities checked.
$amenities_checked = [];

# Check whether the form has been submitted.
if (isset($_POST["list_property"])) {
    # Initialise the amenities string.
    $property_amenities = "";

    # Check whether any checkbox has been checked.
    if (isset($_POST["property_amenities"])) {
        # Update the checked amenities array.
        $amenities_checked = $_POST["property_amenities"];

        # Implode the array into a comma-separated string.
        $property_amenities = implode(",", $amenities_checked);
    }
}

Code for step 3:

# Iterate over every amenity.
while ($row = $stm -> fetch()) {
  # Cache the id and name of the amenity.
  list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]];

  # Check whether the name of the amenity is in the array of the checked ones.
  $checked = in_array($amenity_name, $amenities_checked) ? "checked" : "";

  # Insert the HTML code in the list array.
  $List[] = "<label class = checkbox>
                <input type = checkbox name = 'property_amenities[]'
                       value = '$amenity_name' $checked/>
                $amenity_name
             </label>";
}

Complete Code:

(The snippet is used to collapse the code)

<?php
  $db_host = "localhost";
  $db_name = "cl43-realv3";
  $db_user = "root";
  $db_pass = "";

  # Create a PDO database connection.
  try {
    $DB_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
    $DB_con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch (PDOException $e) {
    $e -> getMessage();
  }

  # Initialise an array to store the amenities checked.
  $amenities_checked = [];

  # Check whether the form has been submitted.
  if (isset($_POST["list_property"])) {
    # Initialise the amenities string.
    $property_amenities = "";
    
    # Check whether any checkbox has been checked.
    if (isset($_POST["property_amenities"])) {
      # Update the checked amenities array.
      $amenities_checked = $_POST["property_amenities"];
      
      # Implode the array into a comma-separated string.
      $property_amenities = implode(",", $amenities_checked);
    }
  }
?>
<!DOCTYPE html>
<html>
  <body>
    <form action = "<?= htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">
      <div class = "row clearfix">
        <div class="col-lg-12 col-md-6 col-sm-12">  
          <?php
            # Fetch the amenities.
            $stm = $DB_con->prepare("SELECT * FROM property_amenities");
            $stm -> execute([]);

            # Iterate over every amenity.
            while ($row = $stm -> fetch()) {
              # Cache the id and name of the amenity.
              list($amenity_id, $amenity_name) = [$row["amenity_id"], $row["amenity_name"]];
              
              # Check whether the name of the amenity is in the array of the checked ones.
              $checked = in_array($amenity_name, $amenities_checked) ? "checked" : "";
              
              # Insert the HTML code in the list array.
              $List[] = "<label class = checkbox>
                           <input type = checkbox name = 'property_amenities[]' value = '$amenity_name' $checked/>
                           $amenity_name
                         </label>";
            }
            
            # Save the number of amenities.
            $allamenities = $stm -> rowCount();
          
            # Determine the number of chunks.
            $how_many_chunks = $allamenities / 3;
            $roster_chunks = array_chunk($List, round($how_many_chunks), true);
          ?>

          <label>Property Amenities</label>

          <?php
            # Iterate over every chunk.
            foreach ($roster_chunks as $roster_chunk_key => $roster_chunk_value) {
              echo "<div class='col-lg-3 col-md-6 col-sm-12'>" . join($roster_chunk_value) . "</div>";
            }
          ?>
        </div> 
      </div>
      <button type = "submit" class = "btn btn-primary" name = "list_property">SUBMIT PROPERTY</button>
    </form>
  </body>
</html>

Upvotes: 2

Progesh Subba
Progesh Subba

Reputation: 66

First you fetch your data from property_listings table and use explode function to convert your property_amenities string into array. Then you can use in_array() function to check your string. If amenity_name exist in your array then you can use checked attribute.

Eg.

$stm = $DB_con->prepare("SELECT * FROM property_amenities");
$stm->execute(array());

// fetch data from property_amenities then use explode function
$property_amenities = explode(",",$data);

      while ($row = $stm->fetch()){
        $amenity_id = $row['amenity_id'];
        $amenity_name = $row['amenity_name']; 
        $List[] ="<label class=checkbox> <input type=checkbox name='property_amenities[]' value='$amenity_name' <?php if(in_array($amenity_name,$property_amenities)){ echo "checked=true"; }?>> $amenity_name</label>";
      } 

Upvotes: 0

Related Questions