Page 1 of 1

Inserting checkbox values into database

Posted: Mon Oct 27, 2008 9:53 pm
by dedurus
Hi to all

I need help for this problem that i'm trying to solve for a while (i'm new in PHP).
I have a form with several checkboxes which values are pulled from a database.
I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database.

Here's the code:

Code: Select all

 
<form id="form1" name="form1" method="post" action="">
<?php
$info_id=$_GET['info_id'];
$kv_dodatoci=mysql_query("SELECT * FROM `dodatoci`") or die('ERROR DISPLAYING: '.mysql_error());
while($kol=mysql_fetch_array($kv_dodatoci)){
    $id_dodatoci=$kol['id_dodatoci'];
    $mk=$kol['mk'];
    
 
  echo '<input type="checkbox" name="id_dodatoci[]" id="id_dodatoci" value="'.$id_dodatoci.'" />';
  echo '<label for="'.$id_dodatoci.'">'.$mk.'</label><br />';
  }
?>
<input type="hidden" value="<?=$info_id?>" name="info_id" />
<input name="insert_info" type="submit" value="Insert Additional info" />
</form>
<?php
if(isset($_POST['insert_info']) && is_array($id_dodatoci)){
        echo $id_dodatoci.'<br />';
        echo $mk.'<br />';
 
// --- Guess here's the problem  ----- //
    foreach($_POST['id_dodatoci'] as $dodatok){
        $dodatok_kv=mysql_query("INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id) VALUES ('$dodatok','$info_id')") or die('ERROR INSERTING: '.mysql_error());
    }
    
}
 
 
?>



my problem is to loop through all checkboxes, and for each checked, populate a separate record in a database.
actually i don't know how to recognize the which box is checked, and put the appropriate value in db.


I hope someone can help me solve this or give me some guideline.

Thanks in advance.

Re: Inserting checkbox values into database

Posted: Mon Oct 27, 2008 10:49 pm
by pcoder
Try this.It will help you to identify the post value.

Code: Select all

 
print_r($_POST);
 

Re: Inserting checkbox values into database

Posted: Tue Oct 28, 2008 12:24 pm
by dedurus
thanks pcoder.
i've tried printing the $_POST array and all the values are correct.
I need a loop which will insert all checked values in the database

Re: Inserting checkbox values into database

Posted: Tue Oct 28, 2008 12:29 pm
by aceconcepts

Code: Select all

 
for($x=0; $x<count($_POST['field']); $x++)
{
//get you fields by $_POST['field'][$x]
}
 

Re: Inserting checkbox values into database

Posted: Tue Oct 28, 2008 8:58 pm
by dedurus
thanks aceconcepts, that was completely helpful and solve my problem.
thanks again.