I have a lot of checkboxes to process in each page of my site. My intention is to store all the check items in the list in irrespective of which page it has been checked.

<?php
session_start();
$category_id=$_GET['cat_id'];
$subcat_id=$_GET['sub_id'];
$page_num=$_GET['page_num'];
$i = 0;
foreach($_POST['id'] as $checkbox){
$_SESSION[$i] = $checkbox;
$i++;
} 
echo "<pre>";
print_r($_SESSION);
echo "</pre>\n"; 

echo '
<table width="400" border="1">
  <form id="myForm" method="<?php $_SERVER["PHP_SELF"];?>" >
  <tr>
    <th width="41" scope="col">Select</th>
    <th width="259" scope="col">Name</th>
    <th width="32" scope="col">QTY</th>
  </tr> 
  <div class="section" id="content">
  ';
  if($result) {
		if(mysql_num_rows($result)>0) {
		        $i=1;
				while ($row = mysql_fetch_array($result))
				 {
				   $item_id = $row["item_id"];
	               $cat_id = $row["cat_id"];
	               $sub_id = $row["sub_id"];
	               $item_name = $row["item_name"];
	               //$type = $row["types"];
				   echo "

				 <tr>
                   <td align='center'><input type='checkbox' name='$item_id' value='$item_name' /></td>
                   <td> $item_name </td>
                   <td align='center'><input type='text' name='qty' size='4'/></td>
                 </tr>

				 ";$i++;
				  }

				 echo'</div> <input type="submit" value="submit"/></form></table> ';
				  }
	else {
	echo" The second id statement defaunkt"; }
}?>

Few more details :
1. the page URL are something like this : http://www.blahblah.com/something.php?cat_id=10 or http://www.blahblah.com/something.php?cat_id=13. Please notice that only cat_id changes which in turn brings items from database under that category.

  1. Once user returns to the page the where he has selected a checkbox, that same checkbox should be shown as selected or checked.

Please help!! Racking my brains for 3 days trying to find this specific solution. Most tutorials have failed me.

Thank you soo much.

    Change the name of the checkboxes to something like id[$item_id]. Then all the (checked) checkboxes will be in a single array named $_POST['id']. That entire array can be stored in the session. You can use functions like [man]array_merge[/man], [man]array_intersect_keys[/man], and [man]array_diff_keys[/man] to combine and remove arrays from different pages from each other depending on what it is you actually want to do with them. Keep in mind that any checkboxes that are not checked in a given form are not included in the submitted post.

      This may turn out to be little more than a rant, but bear with me here.

      I have had a lot of experience working with checkboxes lately, and I've realized a few basic facts:

      1) Checkboxes only POST when they are checked. That means you either have to check whether the checkbox posted, or you have to ignore the non-posting checkboxes.
      2) Checkboxes can be extremely unwieldy to work with in queries, especially if they are POSTed as an array.

      With that in mind, I had to make a major shift in my thinking. Assuming the checkbox values are eventually stored in a database, I had to design with the goal in mind. In other words, my checkboxes are named exactly as they are stored in the database. Everything else become infinitely easier from there.

      The emphasis then gets shifted to query building rather than sifting through POST values. The following code shows how I build the query string:

      // Initialize two parts of the query string:
      $query_left = "INSERT INTO table_name (";
      $query_right = ") VALUES (";
      
      // Add the POST values:
      foreach($_POST as $key => $value)
        {
        // "Submit" is usually your last field on an HTML form, so break:
        if($key == 'submit') break;
      
        // If you are on the last field before submit, you want to skip the comma in the query string:
        if($key == '{second to last field}')
          {
          $query_left .= $key;
      
      // Separate out the numeric fields from the strings:
      if(is_numeric($value))
        {
        $query_right .= $value;
        }
      else
        {
        // Strings will need quotes around them for the query:
        $query_right .= "\"".$value."\"";
        }
      }
        else
          {
          // Include the commas:
          $query_left .= $key.",";
      
      // Separate out the numeric fields from the strings:
      if(is_numeric($value))
        {
        $query_right .= $value.",";
        }
      else
        {
        $query_right .= "\"".$value."\", ";
        }
      }
        }
      
      // Now cap off the ends:
      $query_left .= ")";
      $query_right .= ")";
      
      // And put it together:
      $query = $query_left.$query_right;
      
      // Admire your finished query string, fully ready for database execution!
      echo $query;
      

      Then you can either store this query in a SESSION variable, or use it.

      That leaves the question about maintining POST data without updating the database. The easiest thing (to me) is just to update the database, but hold the primary key in a session variable so you can delete it later if the user doesn't commit the data. That way if the user wants to go back and change something, you can query the database for the appropriate form values. So for example:

      if(isset($_SESSION['primary_key']))
        {
        $pk = $_SESSION['primary_key'];
        // Query the database:
        $query = "SELECT * FROM table WHERE primary_key = $pk";
        $result = mysql_query($query);
        $row = mysql_fetch_array($result);
        extract $row;
        }
      

      Then your HTML would include something like:

      <input type="checkbox" name="field1" value="1"<?php echo isset($field1)?" checked":""; ?>>
      
        ixalmida wrote:

        2) Checkboxes can be extremely unwieldy to work with in queries, especially if they are POSTed as an array.
        ...
        In other words, my checkboxes are named exactly as they are stored in the database.

        So what do you do in the situation (as is the case here) where there are multiple checkboxes representing the values from the same column for multiple records - which is a common reason for putting them into their own sub-array?

          So what do you do in the situation (as is the case here) where there are multiple checkboxes representing the values from the same column for multiple records - which is a common reason for putting them into their own sub-array?

          I would still give them a unique name but with a variable identifier at the end that I can strip off later with substr(). I have had nothing but trouble with POST arrays and it always multiplies the lines of code needed to extract the values.

          I'm not here to argue - I'm just stating my experience. If you have some awesome method that always works for you, name it. Maybe I'll change my mind.

            ixalmida wrote:

            I would still give them a unique name but with a variable identifier at the end that I can strip off later with substr().

            Sounds like you're just trying to implement arrays manually; you don't say whether you use any sort of delimiter between the field name and the key, but whether you do or not you're still having to hand-tool and hand-parse a hand-made array syntax.

            If you have some awesome method that always works for you, name it.

            Only the usual:

            <input type="checkbox" name="fieldname[<?php echo $recordnumber?>]" value="1" />

            I don't really care about the value, because the field won't be there if the checkbox isn't checked. I just want the record numbers. That's

            $checked_fields = array_keys($_POST['fieldname']);

            I'd love to know what's so difficult about that.

            If you have some awesome method that always works for you, name it. Maybe I'll change my mind.

              I'd love to know what's so difficult about that.

              I never said difficult - I said "trouble". I always get errors when trying to work with POST arrays, but your method makes sense and I'll try again.

                Write a Reply...