我有这个代码,我从StackOverflow中获取了这个代码,然后我将表单方法的表单更改为get,它对我来说不起作用。当我检查框时,页面会刷新并调用查询。但是,即使表中有行,查询也不会返回任何行。有什么想法吗?
HTML:
<script>
$(function() {
$('.checkbox').on('change',function(){
$('#form').submit();
});
</script>
<form id="form" method="GET" action="">
<h4>Condition</h4>
<input type="checkbox" name="new" class="checkbox" <?=(isset($_GET['new'])?' checked':'')?>/> New<br/>
<input type="checkbox" name="used" class="checkbox" <?=(isset($_GET['used'])?' checked':'')?>/> Used<br/>
</form>
PHP:
if (isset($_GET["new"])) {
$arguments[] = "`condition` LIKE '%new%'";
}
if (isset($_GET["used"])) {
$arguments[] = " condition LIKE '%use%' ";
}
if( ! empty($arguments)) {
$str = implode(' or ',$arguments);
$fetch = $mydb->prepare("SELECT * FROM table where username = ? and ? ORDER BY id desc");
echo $mydb->error;
$fetch->bind_param('ss', $username, $str);
$fetch->execute();
$result = $fetch->get_result();
//$result->num_rows gives me 0 in this case
} else {
$fetch = $mydb->prepare("select * from table where username = ? order by id desc");
$fetch->bind_param('s', $username);
$fetch->execute();
$result = $fetch->get_result();
//this one works
}
while ($row = $result->fetch_assoc()) {
//echo some rows.
}
答案 0 :(得分:0)
稍微冗长的解决方案(并没有真正告诉你错误但可能有效):
if (isset($_GET["new"]) && !isset($_GET["used"])) {
$fetch = $mydb->prepare("SELECT * FROM table where username = ? and condition LIKE '%new%' ORDER BY id desc");
}
if (!isset($_GET["new"]) && isset($_GET["used"])) {
$fetch = $mydb->prepare("SELECT * FROM table where username = ? and condition LIKE '%use%' ORDER BY id desc");
}
if (isset($_GET["new"]) && isset($_GET["used"])) {
$fetch = $mydb->prepare("SELECT * FROM table where username = ? and condition LIKE '%use%' or condition LIKE '%new%' ORDER BY id desc");
}
if (!isset($_GET["new"]) && !isset($_GET["used"])) {
$fetch = $mydb->prepare("SELECT * FROM table where username = ? ORDER BY id desc");
}
echo $mydb->error;
$fetch->bind_param('s', $username);
$fetch->execute();
$result = $fetch->get_result();
<强>更新强>
我的女儿告诉我,您准备好的语句的真正问题是您尝试将列的名称放入查询中 - 您需要在预准备语句中使用condition LIKE
,并且只添加值{{ 1}}或'%new%'
其中问号是......准备好的语句准备列以供选择。所以你必须至少有三个不同的预备语句(无,一,两个条件) - 你可以动态地生成这些语句,或者使用上面的语句来简化你的生活。