0

Hello i want any checkbox i am gonna check, to stay checked after pagination.

here is the code:

foreach($test as $string){

            $queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. "  ;" ;

            $resultForArray = mysql_query($queryForArray, $con);    
            $rowfForArray = mysql_fetch_array($resultForArray);

?>
    <td  id="<?php echo $rowfForArray["p_id"]?>"   onclick="setStyles(this.id)" ><?php echo  $rowfForArray["p_fname"]?></td>
    <td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox"  name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>" 
    <?php  foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>

I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.

The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)

3 Answers 3

0

In the checkbox tag use the ternary operation, without that foreach inside him:

    <input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />

because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.

I hope I have helped you.

0

A few ways to tackle this:

(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.

(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.

(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.

Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...

0

I did it without touching the database...

The checkbox fields are a php collection "cbgroup[]". I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)

I POST the pagination instead of GET.

After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.

I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)

After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!

First, go through all the checkboxes and clear the array of these values This will only clear the checkboxes from the current page, not any previously checked items from any other page.

if (array_key_exists('currentids', $_POST)) {
          $currentids = $_POST['currentids'];
          if (isset($_SESSION['materials'])  )  {

             if ($_SESSION['materials'] != "") {

                  $text = $_SESSION['materials'];
                  $delimiter=',';
                  $itemList = explode($delimiter, $text);
                  $removeItems = explode($delimiter, $currentids);                  

                  foreach ($removeItems as $key => $del_val) {
                  //echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
                         // Rip through all possibilities of Item IDs from the current page
                         if(($key = array_search($del_val, $itemList)) !== false) {
                             unset($itemList[$key]);
                             //echo "<br>removed ".$del_val;
                         }                           
                        // If you know you only have one line to remove, you can decomment the next line, to stop looping
                        //break;                             
                  }
                  // Leaves the previous paged screen's selections intact
                  $newSessionItems = implode(",", $itemList);                     
                  $_SESSION['materials'] = $newSessionItems;                      
             }
          }
       }

Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all. Check which checkboxes were checked

if (array_key_exists('cbgroup', $_POST)) {
       if(sizeof($_POST['cbgroup'])) {
            $materials = $_POST['cbgroup'];
            $N = count($materials);

            for($i=0; $i < $N; $i++)
                {                   
                $sessionval = ",".$materials[$i];
                $_SESSION['materials'] = $_SESSION['materials'].$sessionval;
                }                    
        } //end size of 
     } // key exists

Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth This reads the entire collection of IDs and removes duplicates, if there are any.

if (isset($_SESSION['materials'])  )  {
   if ($_SESSION['materials'] != "") {

        $text = $_SESSION['materials'];
        $delimiter=',';
        $itemList = explode($delimiter, $text);
        $filtered = array();
            foreach ($itemList as $key => $value){
                if(in_array($value, $filtered)){
                continue;
                }
                array_push($filtered, $value);
            }               
            $uniqueitemschecked = count($filtered);
            $_SESSION['materials'] = null;
            for($i=0; $i < $uniqueitemschecked; $i++)  {
                $_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
            }

   }
}

$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key

Typical form...
<form name="materials_form" method="post" action="thispage.php">

Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth

<input id="_page" name="page" value="<?php echo $page ?> "> 

if ($page < $counter - 1) 
$pagination.= "<a href=\"javascript:document.getElementById('_page').value='$next';materials_form.submit();\"> next »</a>";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";   

Read from your database and populate your table

When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array

echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";                 
                      if (isset($filtered)) {
                         $uniqueitemschecked = count($filtered);
                            for($i=0; $i < $uniqueitemschecked; $i++)  {
                                if ($row[0] == $filtered[$i]) {
                                   echo " checked ";
                                }
                            }
                      }

While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop

...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}

After the loop, write out the hidden text field

echo "<input type='hidden' name='currentids' value='$allcheckboxids'>"; 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.