Jump to content

Preselecting checkboxes based on values in database...


Go to solution Solved by xfilterx,

Recommended Posts

Alright so I got one last issue here as it relates to my project....I have a main standards table. I also have several tables like assets, substrates, organizations, etc. For each standard, several assets can exist. For each standard several substrates can exist, etc. etc. You get the picture. I've attached a DB sample to help visualize. 

 

db.gif

 

There are many more tables but they all look exactly like this....I think you get the picture. So essentially, for every standard, there can be numerous environments and processes associated with it. So let's say one standard (standard_id=1) would have several processes associated with it. So in the standards_process table it could look something like this:

 

1     1     2

2     1     3

3     1     5

 

What I need to do is be able to select the process_id's 2, 3, and 5 from that table and preselect the corresponding checkboxes in the web app. My code looks like this....mind you I have not even attempted to preselect the checkboxes....at this point I'm just pulling the processes and creating a checkbox list on the fly. That works great (I commented out the code that Zane helped me with on the pre-selection of the DropDownList for organizations. That worked great but it was a dropdown list and not a series of independent checkboxes!). 

//Process
echo "<tr><td style='font-weight:bold;vertical-align:top;'>Process</td><td>";
while ($rowProcess = mysqli_fetch_array($process))
{
     //$selected = ($orgid == $rowOrganizations['organization_id']) ? "selected='selected'" : null;
     echo "<input type='checkbox' name='process' value=" . $rowProcess["process_id"] . ">" . $rowProcess["process"] . "<br>"; 
}
echo "</td></tr>";

In ASP.NET this is actually pretty easy. I would dump the table into a Dataset (a collection essentially). Use a For Each loop to loop through that collection. Then use a nested loop to loop through the collection of checkbox items in a CheckBoxList control and select the checkbox item if it's value matches the value in the row within the Dataset. Not sure how to go about doing this in PHP....any help would be greatly appreciated....

Edited by xfilterx

$sql = "select standards_process_id,standard_id,process_id from standards_process $whereclause $order_by;";

$res = mysqli_query($db_conn,$sql);

if ($res) {
   while ($row = mysqli_fetch_assoc($res)) {
      echo "<input type='checkbox' name='process' value=". $rowProcess["process_id"];
      if ($row['process_id'] > 0) echo "selected='selected'";
      echo ">" . $row['somevar'] . "<br />\n";
   }
   echo "</td></tr>\n";
}

I'm probably not understanding something (mean this is meant to stimulate thinking, not be a "drop-in" solution). You do need to use fetch_assoc instead of fetch_array if you want to use string indices on your arrays, though; fetch_array only returns an integer-indexed array...

 

HTH,

Edited by dalecosp
I'm probably not understanding something (mean this is meant to stimulate thinking, not be a "drop-in" solution). You do need to use fetch_assoc instead of fetch_array if you want to use string indices on your arrays, though; fetch_array only returns an integer-indexed array...

HTH,

 

 

mysqli_fetch_array() returns both numeric and associative by default.  You can specify with  MYSQLI_ASSOC or  MYSQLI_NUM with the second optional argument.

Edited by AbraCadaver

What determines if they are preselected?  If your query returns process_ids 2, 3 and 5, which ones are selected?  If all of them then that easy, just add selected="selected" to all the checkboxes.

 

Also, if you have more than one input named process then only the last one will be submitted.  You need to create an array of process checkboxes:  name="process[]".  Then you can access the $_POST['process'] array after submit.

mysqli_fetch_array() returns both numeric and associative by default.  You can specify with  MYSQLI_ASSOC or  MYSQLI_NUM with the second optional argument.

Ah, yes, my bad. I've just gotten in the habit of treating it that way I guess. Hard ever seem to use fetch_array anymore.....

What determines if they are preselected?  If your query returns process_ids 2, 3 and 5, which ones are selected?  If all of them then that easy, just add selected="selected" to all the checkboxes.

 

Also, if you have more than one input named process then only the last one will be submitted.  You need to create an array of process checkboxes:  name="process[]".  Then you can access the $_POST['process'] array after submit.

 

That's the point, I need to select the checkboxes with values of 2, 3, and 5 if those are the values that are returned from the table for standard_id=1. 

 

In terms of your array...I flat out don't know how to do that in PHP. I'm in ASP.NET guy that got thrust into a PHP project. Any pointers would be greatly appreciated.

Try that:

echo "<input type='checkbox' name='process[]' value='" . $rowProcess["process_id"] . "' selected='selected'>" . $rowProcess["process"] . "<br>";

As for the array, I showed you in my post and it is shown in the code above.  In the page that receives the submitted data you woudl loop through $_POST['process'] or concatenate them or whatever you need for the end result (which we haven't seen).

This is what I'm working with:

while ($rowAssets = mysqli_fetch_array($assets))
{
     $assetid = $rowAssets["asset_id"];
     while ($rowSelAssets = mysqli_fetch_array($selectedAssets))
     {
          $selectedAsset = ($assetid == $rowSelAssets['asset_id']) ? "checked" : null;
     }
     echo "<input type='checkbox' name='assets' {$selectedAsset} value=" . $rowAssets["asset_id"] . ">" . $rowAssets["asset"] . "<br>"; 
}

My rationale for writing it like this is...I loop through the main Assets table and display all of the checkboxes with associated values. In total there are 10 including the following:

 

Bridge

Containment Liners
Offshore Structure
Pipeline
Pressure Vessel
Ship Structure
Tank, General Purpose
Tank, Chemical & Solvent
Tank, Caustic Storage
Tank, Potable Water
 
The checkboxes are showing up fine. Next what I do within the loop is set the $assetid variable equal to the asset_id of the current item within the loop. Then I perform a nested loop to loop through the 3 items that are selected within the intermediary table "standards_assets". In that table asset_id's 2, 3, and 5 are set. Within the loop I check to see if $assetid is equal to the asset_id value within that table. If it is, I set $selectedAsset to "checked". Finally I echo out the checkbox...hoping that the checked state would be set....but it is not. Any ideas?

In ASP.NET this is actually pretty easy. I would dump the table into a Dataset (a collection essentially). Use a For Each loop to loop through that collection. Then use a nested loop to loop through the collection of checkbox items in a CheckBoxList control and select the checkbox item if it's value matches the value in the row within the Dataset. Not sure how to go about doing this in PHP....any help would be greatly appreciated....

1. "dump the table into a dataset" ... OK; in PHP, you probably have to setup an array to hold the data, and get your data into it. Show how you're doing that now?

 

Here's an example from something I wrote recently:

 

$x=0;
$plist = array();

while ($row=mysqli_fetch_assoc($res)) {
      $plist[$x]['model']=$row['model'];
      $plist[$x]['url']=$row['url'];
      $plist[$x]['brand']=$row['brand'];
      $x++;
   }//while
2. "For Each loop" ... pretty standard in most any language.

 

3. "Use a nested loop" ... again, pretty standard. I guess we *really* need to see your dataset code.

 

Let me state that the examples we've been showing are using echo() to print the results immediately. There's not any reason it would *have* to be this way; you could certainly create a variable and repeatedly concatenate new text to it to use later or return if this was all wrapped up in a function/class whatever.

 

I don't have any ASP experience in particular; it sounds like you just need to think a little "deeper" into what you actually want the software to do. And perhaps that's too easy for me to say; I've been used to doing PHP for years and grabbing a dataset as I did above is very plain, boring work for me these days. Maybe it isn't for you yet. I'm sure if I were thrust into a .NET project I'd be the one asking *you* for help ... :-)

The checkboxes are showing up fine. Next what I do within the loop is set the $assetid variable equal to the asset_id of the current item within the loop. Then I perform a nested loop to loop through the 3 items that are selected within the intermediary table "standards_assets". In that table asset_id's 2, 3, and 5 are set. Within the loop I check to see if $assetid is equal to the asset_id value within that table. If it is, I set $selectedAsset to "checked". Finally I echo out the checkbox...hoping that the checked state would be set....but it is not. Any ideas?

What exactly IS being output to the browser?

1. "dump the table into a dataset" ... OK; in PHP, you probably have to setup an array to hold the data, and get your data into it. Show how you're doing that now?

 

Here's an example from something I wrote recently:

 

$x=0;
$plist = array();

while ($row=mysqli_fetch_assoc($res)) {
      $plist[$x]['model']=$row['model'];
      $plist[$x]['url']=$row['url'];
      $plist[$x]['brand']=$row['brand'];
      $x++;
   }//while
2. "For Each loop" ... pretty standard in most any language.

 

3. "Use a nested loop" ... again, pretty standard. I guess we *really* need to see your dataset code.

 

Let me state that the examples we've been showing are using echo() to print the results immediately. There's not any reason it would *have* to be this way; you could certainly create a variable and repeatedly concatenate new text to it to use later or return if this was all wrapped up in a function/class whatever.

 

I don't have any ASP experience in particular; it sounds like you just need to think a little "deeper" into what you actually want the software to do. And perhaps that's too easy for me to say; I've been used to doing PHP for years and grabbing a dataset as I did above is very plain, boring work for me these days. Maybe it isn't for you yet. I'm sure if I were thrust into a .NET project I'd be the one asking *you* for help ... :-)

 

 

Yeah I posted my code. It seems like my nested loop is correct...not sure why it's not setting $selectedAsset to "checked". 

What exactly IS being output to the browser?

 

Nothing. There's an empty space where "checked" should be in code.

 

Also, I did some other outputs and the standard_assets table is being connected to and data is being read correctly. No issues there. The problem is with the nested loop.

Edited by xfilterx

Yeah it's valid. Modified my code slightly to look like this:

//while ($rowAssets = mysqli_fetch_array($assets))
//{
//   $assetid = $rowAssets["asset_id"];
     while ($rowSelAssets = mysqli_fetch_array($selectedAssets))
     {
          //$selectedAsset = ($assetid == $rowSelAssets['asset_id']) ? "checked" : null;
          echo "<input type='checkbox' name='assets' value='" . $rowSelAssets["asset_id"] . "'>" . $rowSelAssets["asset_id"] . "<br>"; 
     }
     //echo "<input type='checkbox' name='assets' {$selectedAsset} value='" . $rowAssets["asset_id"] . "'>" . $rowAssets["asset"] . "<br>"; 
//}

And it spits out (with checkboxes next to them):

 

2
3
5

 

So yeah, that appears to be working...

Edited by xfilterx

Tried something a little different but getting the same result. $selectedAsset is null.

$arrAssets[] = mysqli_fetch_array($selectedAssets);
while ($rowAssets = mysqli_fetch_array($assets))
{
     $assetid = $rowAssets["asset_id"];
     if (in_array($assetid, $arrAssets)) {
          $selectedAsset = "checked";
     } else {
          $selectedAsset = null;
     }     
     echo "<input type='checkbox' name='assets[]' {$selectedAsset} value='" . $rowAssets["asset_id"] . "'>" . $rowAssets["asset"] . "<br>";}

This seems to make sense. Dump the selected asset_ids into an array ($arrAssets). Within the loop check to see if the assetid exists within the array. If it does, set a variable to checked. If it doesn't, set it to null. Unfortunately it's always null. Should be 2, 3, and 5 that are the selected checkboxes....

Also tried it this way....same thing...nothing is checked.

$arrAssets = array();
while($row = mysqli_fetch_array($selectedAssets))
{
    $arrAssets[] = $row;
}
        
//echo $arrAssets[2]['asset_id']; //Debug
        
while ($rowAssets = mysqli_fetch_array($assets))
{
    $assetid = $rowAssets["asset_id"];
    foreach($arrAssets as $value)
    {
        if($assetid==$value) {
            $selectedAsset = "checked";
        } else {
            $selectedAsset = null;
        }
    }
                       
    echo $assetid; //Debug
    echo "<input type='checkbox' name='assets[]' {$selectedAsset} value='" . $rowAssets["asset_id"] . "'>" . $rowAssets["asset"] . "<br>"; 
}
Edited by xfilterx
  • Solution

So I got it working. Not sure if this is the most elegant solution but this works.

$arrAssets = array();
while($row = mysqli_fetch_array($selectedAssets))
{
    $arrAssets[] = $row;
}       
while ($rowAssets = mysqli_fetch_array($assets))
{
    $assetid = $rowAssets["asset_id"];
    for ($x = 0; $x < count($arrAssets); $x ++)
    {
        if($arrAssets[$x]["asset_id"] == $assetid) {
            $selectedAsset = "checked";
            break;
        } else {
            $selectedAsset = null;
        }
    } 
    echo "<input type='checkbox' name='assets[]' {$selectedAsset} value='" . $rowAssets["asset_id"] . "'>" . $rowAssets["asset"] . "<br>"; 
}

This is about all of my 72 hours of PHP knowledge could muster. I think I'd be dangerous had I started using PHP back in the early 2000's when I first learned ASP.NET.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.