首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于复选框在PHP中运行SQL查询

基于复选框在PHP中运行SQL查询
EN

Stack Overflow用户
提问于 2014-04-30 22:17:20
回答 2查看 502关注 0票数 0

我在PHP中运行这个SQL查询:

代码语言:javascript
复制
$stmt = $pdo_conn->prepare("SELECT * from porting order by field(status, 'Submitted', 'Rejected', 'Cancelled', 'Accepted') ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

但我希望能够添加复选框来修改查询,而无需刷新页面

例如,

代码语言:javascript
复制
<input type="checkbox" name="status" value="Submitted" />
<input type="checkbox" name="status" value="Rejected" />
<input type="checkbox" name="status" value="Cancelled" />
<input type="checkbox" name="status" value="Accepted" />

因此,如果检查了值为“Submitted”的输入,则查询将更改为:

代码语言:javascript
复制
SELECT * from porting where status = 'Submitted'

如果同时选中了值为“Submitted”和“Accepted”的输入,则查询将为:

代码语言:javascript
复制
SELECT * from porting where status = 'Submitted' or status = 'Accepted'
EN

回答 2

Stack Overflow用户

发布于 2014-04-30 22:25:34

复选框应使用数组语法

代码语言:javascript
复制
<input type="checkbox" name="status[]" value="Submitted" />
<input type="checkbox" name="status[]" value="Rejected" />
<input type="checkbox" name="status[]" value="Cancelled" />
<input type="checkbox" name="status[]" value="Accepted" />

从那里开始,你就是implode

代码语言:javascript
复制
$sql = "SELECT * from porting where status IN('".implode("', '", $_POST['status'])."')";

警告:上面的SQL查询容易受到 的攻击,但它应该会让您走上正确的道路。

票数 2
EN

Stack Overflow用户

发布于 2014-04-30 22:34:05

代码语言:javascript
复制
$checkboxes = $_POST['status'];
if(count($checkboxes)) {
    $where_clause = ' where';
}
else {
    $where_clause = '';
}
foreach($checkboxes as $el) { $el = addslashes($el);
   $where_clause .= " status = '$el' or";
}
$where_clause = substr($where_clause, 0, -2);

$query = 'select * from porting' . $where_clause;

最后,$query将包含如下字符串:

代码语言:javascript
复制
select * from porting where status = 'Submitted' or status = 'Cancelled'

如果你想发送多个值,你应该使用name="status[]"而不是name="status"

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23390592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档