How to insert multiple check-box values inside database when one or more will be left unchecked?
I have a form that contains 5 check boxes. The user may select one or more of these check boxes. The user may select 2 and leave 3 unchecked or select 4 and leave one unchecked and so on, in that case how can I write the php/mysql code that will insert the form data into the database. With just one selection it's easy, I would do:
$checkbox_value = $_POST['i_agree'];
mysql_query("INSERT INTO terms (user, pass, conditions) VALUES ('$user','$pass','$checkbox_value')");
But how can I write this when there are multiple check box options and only one or more of them will be checked?
I wa开发者_开发百科nt to insert them all in one column called "tags" separated by commas.
<?php
<body>
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="a">
<input type="checkbox" name="checkbox[]" value="b">
<input type="checkbox" name="checkbox[]" value="c">
<input type="checkbox" name="checkbox[]" value="d">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<?
/* and in your checkbox.php you do this: */
if(isset($_POST['Submit']))
{
for ($i=0; $i<count($_POST['checkbox']);$i++) {
$check_val .= $_POST['checkbox'][$i];
$check_val .=",";
}
}
?>
Now $check_val will have all checked box values , Now you can put into your database.
<html>
<body>
<form action="" method="post">
<table>
<tr>
<td>Football</td><td><input name="region[]" type="checkbox" value="football">
</td>
</tr>
<tr>
<td>Handball</td><td><input name="region[]" type="checkbox" value="handball">
</td>
</tr>
<tr>
<td>Baseball</td><td><input name="region[]" type="checkbox" value="handball">
</td>
</tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>
<?php
include("connection.php");
foreach($_POST['region'] as $value)
{?
<?php $sql = mysql_query("INSERT INTO sports SET region = '" . implode(',', $_POST['region']) . "'");
}
?>
精彩评论