如何获取复选框 [英] How to fetch checkbox
本文介绍了如何获取复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的HTML代码:
This is my HTML code:
<input type='checkbox' name='cbox[]' value='Jaywalking'/>
Jaywalking<br/>
<input type='checkbox' name='cbox[]' value='Littering'/>
Littering<br/>
<input type='checkbox' name='cbox[]' value='Illegal Vendor'/>
Illegal Vendor
这是我的邮递区号:
if(is_array($_POST['cbox']))
$violation_save=implode(',',$_POST['cbox']);
else
$violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET violation='$violation_save' WHERE id='$id'") or die mysql_error());
如何从数据库中获取选定的值?
How can I fetch the selected values from the database?
推荐答案
首先,您不应该再使用php的mysql_ *函数.这些功能被标记为已弃用,并将在下一个主要的php版本中删除.
First of all you should NOT use the mysql_* functions of php anymore. These functions are marked as deprecated and will be removed in the next major php release.
因此,如果$ _POST ['cbox']是一个数组,则必须将其作为数组处理.
So if $_POST['cbox'] is an array, you must handle it as an array.
// how to save checked values
try {
$db = new PDO(...);
$stmt = $db->prepare("UPDATE yourTable SET myField = :myField WHERE id = :id");
$stmt->bindParam(':id' , $id, PDO::PARAM_INT);
foreach ($_POST['cbox'] as $myField) {
$stmt->bindParam(':myField', $myField);
$stmt->execute();
}
} catch (PDOException $e) {
// error handling
}
// how to fetch checked values
try {
$myValues = array();
$db = new PDO(...);
$stmt = $db->prepare("SELECT myField FROM myTable WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$myValues[] = $row['myField'];
}
} catch (PDOException $e) {
// error handling
}
// HTML Part
<input type="checkbox" name="cbox[]" value="bla"<?php if (in_array('bla', $myValues)) { ?> checked="checked"<?php } ?> />
只需看一下PDO或MySQLi扩展的php手册.
Just have a look at the php manual for PDO or the MySQLi extension.
这篇关于如何获取复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文