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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.