嗨,我是php新手并尝试使用搜索框,我创建了一个表单,如下所示
<form method="post" action="search.php">
<select name="purpose">
<option value="" selected="selected">-any-</option>
<option value="For Sale">For Sale</option>
<option value="For Rent">For Rent</option>
</select>
<select name="type">
<option value="" selected="selected">-any-</option>
<option value="Bungalow">Bungalow</option>
<option value="Apartment">Apartment</option>
</select>
<select name="location">
<option value="" selected="selected">-any-</option>
<option value="Norway">Norway</option>
<option value="Itley">Itley</option>
</select>
<input type="submit" value="Search">
</form>
的search.php
我正在尝试这些问题,但遇到问题
$purpose=$_POST['purpose'];
$type=$_POST['type'];
$location=$_POST['location'];
如果我像这样放置AND查询
SELECT * FROM test WHERE purpose='$purpose' AND location='$location' AND type='$type'
然后它不会逐个过滤结果它显示为空白
如果我像这样进行OR查询
SELECT * FROM test WHERE purpose='$purpose' OR location='$location' OR type='$type'
然后它过滤混合结果
我希望如果所有人都选择它过滤(目的&gt;&gt;类型&gt;&gt;位置)并且如果选择了一个然后按此过滤但是确切的结果 否则显示
Result not found!
先生,我这样做但显示错误
$ qry =“SELECT * FROM test WHERE 1 = 1”;
如果($目的!= “”) $ qry。=“AND purpose ='$ purpose'”;
如果($位置!= “”) $ qry。=“AND location ='$ location'”;
如果($类型!= “”) $ qry。=“AND type ='$ type'”;
while($ row = mysql_fetch_array($ sql))
echo $ row ['purpose'];
echo $ row ['location'];
echo $ row ['type'];
我希望如果不匹配显示结果未找到,否则它将按所有和逐个过滤
答案 0 :(得分:2)
获取变量后放置:
$sql = array();
if (!empty($purpose)) {
$sql[] = "purpose='$purpose'";
}
if (!empty($type)) {
$sql[] = "type='$type'";
}
if (!empty($location)) {
$sql[] = "location='$location'";
}
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM test" . (!empty($sql)?: " WHERE " . $sql: '');
编辑:看到您的评论后
首先,您应该使用mysql_connect函数建立与数据库的连接。比如说,你有这段代码:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
在$ link var中你现在有了你的mysql句柄。这段代码必须放在你想要使用mysql连接的每一页的第一页。一旦你有了SQL语句(在我第一次编写的代码中,$ sql var),请在以下后面使用:
$result = mysql_query($sql);
if (mysql_num_rows($result) === 0) {
echo 'Result not found';
}
while ($row = mysql_fetch_array($result)) {
echo $row['purpose'] . '<br/>';
echo $row['location'] . '<br/>';
echo $row['type'];
}
答案 1 :(得分:0)
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";