我一直在为这个简单的脚本获取一个空查询错误。有什么想法吗?
我只有一个带有输入框和按钮的表单,在表单外面我有一个名为filter1的下拉列表,其中包含3个值“Whole Site”,“Pages”,“Blog”。
<?php
//process the search query
if (isset($_POST['submitted'])) {
require('db_conn.php'); // connect to db
$search_query = $_POST['searchquery'];
// check filter
if ($_POST['filter1'] == 'Whole Site') {
$q = "(SELECT id, page_title AS title FROM pages WHERE page_title LIKE '%$searchquery%' OR page_body LIKE '%$searchquery%') UNION (SELECT id, blog_title AS title FROM blog WHERE blog_title LIKE '%$searchquery%' OR blog_body LIKE '%$searchquery%')";
}
else if ($_POST['filter1'] == 'Pages') {
$q = "SELECT id, page_title AS title FROM pages WHERE page_title LIKE '%$searchquery%' OR page_body LIKE '%$searchquery%'";
}
else if ($_POST['filter1'] == 'Blog') {
$q = "SELECT id, blog_title AS title FROM blog WHERE blog_title LIKE '%$searchquery%' OR blog_body LIKE '%$searchquery%'";
}
$r = mysqli_query($dbc, $q); // query the db
$count = mysqli_num_rows($r);
if ($count > 1) {
$search_output = 'ok';
}
else {
$search_output = "<hr />0 results for <strong>$search_query</strong><hr />$q";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h2>Search the tables</h2>
<form action="search.php" method="post">
<p>Search: <input type="text" name="searchquery"/></p>
<p><input type="submit" name="submit" value="Search"/></p>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
<br/>
Search in:
<select name="filter1">
<option value="Whole Site">Whole site</option>
<option value="Pages">Pages</option>
<option value="BLog">Blog</option>
</select>
<?php echo $search_output; ?>
</body>
</html>
答案 0 :(得分:5)
问题是您的表单过早关闭。名为filter1
的SELECT未包含在您的表单中。
以这种方式重写您的表单:
<form action="search.php" method="post">
<p>Search: <input type="text" name="searchquery"/></p>
<p><input type="submit" name="submit" value="Search"/></p>
<input type="hidden" name="submitted" value="TRUE"/>
<br/>
Search in:
<select name="filter1">
<option value="Whole Site">Whole site</option>
<option value="Pages">Pages</option>
<option value="BLog">Blog</option>
</select>
</form>
答案 1 :(得分:0)
我认为使用开关
时效果更好switch ($_POST['filter1']) {
case 'Whole Site': $q = "(SELECT id, page_title AS title FROM pages WHERE page_title LIKE '%$searchquery%' OR page_body LIKE '%$searchquery%') UNION (SELECT id, blog_title AS title FROM blog WHERE blog_title LIKE '%$searchquery%' OR blog_body LIKE '%$searchquery%')";
case 'Pages': $q = "SELECT id, page_title AS title FROM pages WHERE page_title LIKE '%$searchquery%' OR page_body LIKE '%$searchquery%'";
case 'Blog': $q = "SELECT id, blog_title AS title FROM blog WHERE blog_title LIKE '%$searchquery%' OR blog_body LIKE '%$searchquery%'";
default: $q = false;
}
if($q) {
//Your code
}