tags:

views:

4631

answers:

8

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:

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

+3  A: 

Hi,

You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all.

What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML.

Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate):

HTML:

<input type='checkbox' name='ShowCloseWindowLink' value='1'/> Show the 'Close Window' link at the bottom of the form.

PHP:

if (isset($_POST["ShowCloseWindowLink"])) {
    $ShowCloseWindowLink=1;
} else {
    $ShowCloseWindowLink=0;
}

        .....


$sql = "update table set ShowCloseWindowLink = ".mysql_real_escape_string($ShowCloseWindowLink)." where ..."

(assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)

Eli
Wow... can you refactor that to: $showCloseWindowLink = isset($_POST["ShowCloseWindowLink"]);?
Huppie
Yes, but this is easily readable sample code for someone who may not know much about isset.
Eli
A: 

Hoi!

Well, as Eli wrote, the POST is not set, when a checkbox is not checked.

I sometimes use an additional hidden field (-array) to make sure, I have a list of all checkboxes on the page.

Example:

<input type="checkbox" name="my_checkbox[<?=$id_of_checkbox?>]">
<input type="hidden" name="array_checkboxes[<?=$id_of_checkbox?>]" value="is_on_page">

So I get in the $_POST:

array(2){
 array(1){"my_checkbox" => array(1){[123]=>"1"}}
 array(1){"array_checkboxes" => array(1){[123]=>"is_on_page"}}
}

I even get the second line, when the checkbox is NOT checked and I can loop through all checkboxes with something like this:

foreach ($_POST["array_checkboxes"] as $key => $value)
{
  if($value=="is_on_page")
  {
    $value_of_checkbox[$key] = $_POST["my_checkbox"][$key];
    //Save this value
  }
}

Hope this helps! :)

Best regards, Bastian

bastianhuebner
A: 

As an extra note: You're using the wrong HTML syntax for IDs and <label>. <label>'s "for" attribute should point to an ID, not a value. You also need unique IDs for each element. The code you have posted would not validate.

Also, you're not validating your code at all. At the very least, do a htmlspecialchars() or htmlentities() on the input before you output it and a mysql_real_escape_string() before you insert data into the DB.

Ryan McCue
A: 

Thanks to Ryan, Eli and bastianhuebner for the tips. Anyway something isn't clear to me: I have primary key for each checkbox that is pulled from the database, and i need that primary key to insert into other table. The problem is that those primary keys are dynamic, which makes me unable to insert ta static value to the checkboxes. Actually I need to insert all values of the checked boxes into database. I took a look at your code examples, and yet cannot figure out where the problem lies.

Sorry, i don't have enough reputation to Vote Up your answers :(

dede
A: 

2nd Answer:

You might do something like this:

HTML:

echo '<input type="checkbox" name="id_dodatoci[]" value="'.$id_dodatoci.'" />';

PHP:

if ( !empty($_POST["id_dodatoci"]) ) {
    $id_dodatoci = $_POST["id_dodatoci"];
    print_r($id_dodatoci);
    // This should provide an array of all the checkboxes that were checked.
    // Any not checked will not be present.
} else {
    // None of the id_dodatoci checkboxes were checked.
}

This is because you are using the same name for all of the checkboxes, so their values will be passed to php as an array. If you used different names, then each would have it's own post key/value pair.

This might help too:

http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php

Eli
A: 

Also something that few people use but that is quite nice in HTML, is that you can have:

<input type="hidden" name="my_checkbox" value="N" />
<input type="checkbox" name="my_checkbox" value="Y" />

and voila! - default values for checkboxes...!

Bertrand Gorge
A: 

OK, finally i made it (thanks to Eli and all others). The code is the following:

if(isset($_POST['id_dodatoci'])){


    $id_dodatoci=$_POST['id_dodatoci'];
    $arr_num=count($id_dodatoci);
    $i=0;
    while ($i < $arr_num)
   {

      $query="INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id) 
 VALUES ('$id_dodatoci[$i]','$info_id')";
    $res=mysql_query($query) or die('ERROR INSERTING: '.mysql_error());
      $i++;
    }

   }

This is the loop that i needed, and thanks to you girls and guys, I realized that I need a loop through each key with the $i variable.

Thanks again

dede
A: 

Thank you for the code - I had it working wonderfully and then something went wrong... any other eyes would be appreciated

 $summer_weeks=$_POST['summer_camp'];
$sum_num=count($summer_weeks);
$i=0;
while ($i < $sum_num)

{

$query = "INSERT INTO summer09 (user_id, reg_date, fn, ln, mm, ff, ad, ct, pr, po, home, cell, work, em, gd, month, day, year, hg, ss, sc, can, rel, car, cm) VALUES (NULL, NOW(),'$first_name', '$last_name', '$mother_name','$father_name','$address','$city','$province','$postal','$home_number','$cell_number','$work_number','$email','$gender','$month', '$day','$year','$height','$shirt_size','$summer_weeks[$i]', '$policy_cancel','$policy_release','$carpool','$comments')"; //$result = mysql_real_escape_string ($query); $result = @mysql_query ($query); $i++; }

checkbox name=summer_camp[]

it was inserting a row in mysql for each week selected and now their is just one entry.

Any ideas? Thank you