我带着一点愚蠢的问题来到这里我从复选框中检索了所有选中的值并将值存储在数据库中,但我想将所有选中的值从复选框存储到单个变量,就像我想要绑定所有值一样而不是想将它存储在单个数据库列中。这是我的一点努力。
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("checkboxes",$con);
if(isset($_POST["Submit"]))
{
$checkbox1 = $_POST['chk1'];
$i=0;
$user="admin";
$store;
while($i<sizeof($checkbox1)) {
echo $checkbox1[$i];
$query="INSERT INTO `speciman`(`type`, `user`) VALUES ('".$checkbox1[$i]."','".$user."')";
mysql_query($query) or die ('Error updating database');
$store=$checkbox1[$i];
$i++;
}
echo '<br/>';
echo "Record is inserted.";
}
else
{
}
?>
表格就在这里。
<form action="" method="post" enctype="multipart/form-data">
<input type="checkbox" name="chk1[]" value="blood">blood<br />
<input type="checkbox" name="chk1[]" value="bone">bone<br />
<input type="checkbox" name="chk1[]" value="urine">urine<br />
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
答案 0 :(得分:1)
$store = array(); // initialize $store variable as array
// then loop through the checkboxes and store the values in $store
// you have already written the loop... so now you have the values in $store and it is an array
// then use implode to convert the array to a string
$comma_separated = implode(",", $store);
// http://in1.php.net/function.implode <- implode doc reference
// to get back the values from imploded data, use explode http://in3.php.net/explode
答案 1 :(得分:1)
您可以使用PHP函数serialize(),它将数组转换为字符串。要选择返回,请使用unserialize()
例如:
$data = array(
'1' => 'value1',
'2' => 'value2',
'3' => 'value3',
'4' => 'value4'
);
$newstring = serialize( $data );
/* This will return:
@
@ a:4:{i:1;s:6:"value1";i:2;s:6:"value2";i:3;s:6:"value3";i:4;s:6:"value4";}
@
*/
@mysql_query("INSERT INTO `example` (`id`, `data`) VALUES('', $newstring)") or die('Error: ' . mysql_error());