Php: multiple checkboxes

2019-09-19 05:50发布

I have the following checkbox created by a loop:

<input type='checkbox' value=0 name='<?php echo $question_id; ?>' />

Each checkbox will have a different ID, and when the user checks several checkboxes, I would like to gather all the id's and insert it into a table that relates an 'event' table with a 'questions' table.

However I am not getting the ids...I know I am supposed to use an array, but is that in the name attribute or the values attribute? Also, how do I pass on the IDs...does that go into the values field?

标签: php mysql
4条回答
Melony?
2楼-- · 2019-09-19 05:59

Your html:

<form method="post" action="">
<input type="checkbox" id="things[]" value="red"> Cat<br>
<input type="checkbox" id="things[]" value="blue"> Mouse<br>
<input type="checkbox" id="things[]" value="green"> Car<br>
<input type="checkbox" id="things[]" value="yellow"> DaniWeb
</form>

Your PHP:

<?php
$things = serialize($_POST['things']);

$query = "INSERT INTO table(things) values($things)";
mysql_query($query) or die(mysql_error());
?>
查看更多
forever°为你锁心
3楼-- · 2019-09-19 06:10

I believe you need something like ..

<input type='checkbox' value=<SOME UNIQUE VALUE> name='field_name[]' />

You'll loop through the field_name which happens to be an array.

查看更多
家丑人穷心不美
4楼-- · 2019-09-19 06:11

Try changing your input to this.

<input type='checkbox' value='<?php echo $question_id; ?>' name='questions[]' />

Now when you get the post with php it will return an array with all the question ids

$questionIds = $_POST['questions'];
查看更多
smile是对你的礼貌
5楼-- · 2019-09-19 06:20

In HTML:

<input type='checkbox' value=1 name='checkboxname[<?php echo $question_id; ?>]' />

In PHP:

$set_checkboxes = array_keys($_POST['checkboxname']);

Or, alternatively:

In HTML:

<input type='checkbox' value="<?php echo $question_id; ?>" name='checkboxname[]' />

In PHP:

$set_checkboxes = $_POST['checkboxname'];
查看更多
登录 后发表回答