我有一个博客,我正在使用PHP从数据库中选择文章。问题是因为我的搜索条件我遇到了错误。这是我的代码:
<?php
if(isset($_GET["cat"])){
$cat = $_GET["cat"];
}else{
$cat = "all";
};
?>
<?php
if($cat == "all"){
$cat_var = "";
}else{
$cat_var = "WHERE cat = '$cat'";
}; // NOTE THIS LINE
?>
<?php
if(isset($_GET["issue"])){$issue = $_GET["issue"];}else{
$issue = "all";
};
?>
<?php
if($issue == "all"){
$issue_var = "";
$limit = 4;
}
else{
$issue_var = "AND issue = '$issue'"; // NOTE THIS LINE
$limit = 200;
};
?>
<?php
$count_posts_sql = "SELECT id FROM articles $cat_var $issue_var"; // NOTE THIS LINE
$count_posts_res = mysqli_query($con, $count_posts_sql);
$num_init_posts = mysqli_num_rows($count_posts_res);
//If None, Then Exit
if($num_init_posts == 0){
header("Location: /home");
exit();
}
...
?>
所以我的网址是http://website.com/articles/all/2015-10
,这就是我想要的。但是$cat_var
&amp; $issue_var
导致错误,因为它正在选择:
SELECT * FROM articles AND issue = '2015-10' // NO WHERE STATEMEMT IS SHOWN
如何克服此错误?
答案 0 :(得分:1)
你可以通过坚持WHERE 1=1
进入
$count_posts_sql = "SELECT id FROM articles WHERE 1=1 $cat_var $issue_var"; // NOTE THIS LINE
这是因为你从AND value = 1
开始而没有启动WHERE
子句,这会产生无效的查询。
然后从此行中取出WHERE
并将其替换为AND
:
$cat_var = "AND cat = '$cat'";
答案 1 :(得分:1)
您可以像这样初始化where查询字符串:
$where = 'WHERE 1 = 1 ';
并且可以根据您的输入进行连接。