【发布时间】:2011-07-18 18:22:52
【问题描述】:
更新 2:
无论选中哪些选项,以下内容都会给我UDPATE table SET db_field1=0, dbfield2=0, dbfield3=0, dbfield4=0 WHERE 1=1:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$fields = array('db_field1'=>'cb1', 'dbfield2'=>'cb2', 'dbfield3'=>'cb3', 'dbfield4'=>'cb4');
$update = '';
foreach($fields as $dbfield => $field) {
if ($update) $update.= ',';
$update.= ' '.$dbfield.'=';
if (isset($_POST[field])) {
$update.= 1;
} else {
$update.= 0;
}
}
echo 'UDPATE table SET'.$update.' WHERE 1=1';
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="cb1" />
<input type="checkbox" name="cb2" />
<!-- all the way to 50 -->
<input type="checkbox" name="cb3" />
<input type="checkbox" name="cb4" />
<input type="submit" value="submit" />
</form>
</body>
</html>
更新 1:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST["cb"] ) ) {
$update = "";
foreach ($_POST['cb'] as $key => $value) {
if ( $update ) $update.= ', ';
$update .= $key . " = 1";
}
echo "update table1 set " . $update . " where uid = 10";
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="cb[col1]" />
<input type="checkbox" name="cb[col2]" />
<!-- all the way to 50 -->
<input type="checkbox" name="cb[col3]" />
<input type="checkbox" name="cb[col4]" />
<input type="submit" value="submit" />
</form>
</body>
</html>
原始问题:
我有一个带有许多复选框的 PHP 表单,允许用户选择打开或关闭哪些选项。
返回选中的复选框的最佳方法是什么,以便我可以将数据作为 0 或 1 插入数据库?
我有以下代码,但如果我对所有 50 个复选框都使用此方法,这似乎有点过分:
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST["cb1"] ) ) {
// insert 1 in relevant database table cell
echo 1;
} else {
// insert 0 in relevant database table cell
echo 0;
}
if( isset( $_POST["cb2"] ) ) {
// insert 1 in relevant database table cell
echo 1;
} else {
// insert 0 in relevant database table cell
echo 0;
}
// all the way to 50
if( isset( $_POST["cb49"] ) ) {
// insert 1 in relevant database table cell
echo 1;
} else {
// insert 0 in relevant database table cell
echo 0;
}
if( isset( $_POST["cb50"] ) ) {
// insert 1 in relevant database table cell
echo 1;
} else {
// insert 0 in relevant database table cell
echo 0;
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<input type="checkbox" name="cb1" />
<input type="checkbox" name="cb2" />
<!-- all the way to 50 -->
<input type="checkbox" name="cb49" />
<input type="checkbox" name="cb50" />
<input type="submit" value="submit" />
</form>
</body>
</html>
【问题讨论】: