Jump to content

Keeping checkboxes checked after post... ??


simplyrichard

Recommended Posts

Can someone help me format these two codes together?

 

<?PHP
  $query="SELECT activities_id, activities_name FROM culvercareers.activities"; 
  $result = mysql_query ($query);
  while($nt=mysql_fetch_array($result))
  {
  //Array or records stored in 
  echo "<input type=checkbox name=activities value=$nt[activities_id]> $nt[activities_name] <br>";
}
  echo "</select>";
  ?>

 

(The above code pulls the activities from the database.) and ....

 

<?php if ($_POST['activities'] == $nt[activities_name]) { echo "checked"; } ?>

 

What I am trying to do is if an error happens, the checkboxes on my form are still checked....

Link to comment
https://forums.phpfreaks.com/topic/126631-keeping-checkboxes-checked-after-post/
Share on other sites

OK, I see. First of all, you need [] brackets after "activities" in your checkbox name, so it will be treated as an array. If you don't do that, you'll only get one value of all the checked values.

 

Then, you'll need to check that array for matching values. This should work:

 

<?php
  $activities = isset($_POST['activities'])?$_POST['activities']:array();
  $query="SELECT activities_id, activities_name FROM culvercareers.activities"; 
  $result = mysql_query ($query);
  while($nt=mysql_fetch_array($result))
  {
  //Array or records stored in 
  echo "<input type='checkbox' name='activities[]'".(in_array($nt['activities_id'],$activities)?" checked":"")." value='{$nt['activities_id']}'> {$nt['activities_name']} <br>";
}
?>

 

I also fixed a lot of your syntax. Be careful about that, because using incorrect syntax may work, but then something may go wrong down the road that will screw you up.

F1Fan ,

Using your code above, it worked perfect. However now when I try to insert the selected activities into the database I get only "array" inserted. I assume I need to do something like this

 

$aoi = $activities['0'].$activities['1'].$activities['2'].$activities['3'];

 

That didnt work  >:( nor did $aoi =

$_POST['activities'];

 

Can you help?

 

Richard

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.