Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

php - Inserting checkbox values into database

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...