我在使用php作为输入和输出开发高级搜索代码时遇到了问题,sql用于选择和过滤数据..
php代码:
<form action="index.php?Type=Advance" method="post">
<input type="text" name="name">
<input type="text" name="sponsor">
<select size="1" name="gender" id="">
<option value="male">male</option>
<option value="female">female</femal>
</select>
<select size="1" name="address" id="">
<option value="x">x</option>
<option value="y">y</option>
<option value="z">z</option>
</select>
<input type="submit">
</form>
然后我宣布变量
公共职能AdvanceSearch($ name,$ sponsor,$ gender,$ address) {
$cheack = "";
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
}
if(isset($sponsor)&&$sponsor != ""){
$cheack.=" AND sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
$cheack.=" AND gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
$cheack.=" AND workplace = '$address' ";
}
$DB = mysql_query("SELECT * FROM table WHERE 1 = 1 ".$cheack);
echo "SELECT * FROM user WHERE ".$WHQ;
exit();
实际上它可以工作,但是如果我没有插入名称...... sql语句将是这样的
SELECT *
FROM table
WHERE AND sponsor = 'www'
AND gender = 'male'
如果我想搜索表但没有插入名称怎么办...如果我没有插入名称,我怎么能让sql语句有效。
答案 0 :(得分:3)
对此的典型解决方案是始终首先添加真实条件,例如1=1
。没有任何额外条件的查询将成为
SELECT * FROM table WHERE 1=1
当你添加任何AND
条件时,你可以将它们添加到最后,没有特殊情况的第一个或最后一个条件:
SELECT * FROM table WHERE 1=1 AND sponsor = 'www' AND gender = 'male'
请注意,如果您使用OR代替AND,则第一个条件应为false,例如0=1
。
答案 1 :(得分:0)
您可以使用以下标志变量:
$cheack = "";
$flag = False;
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
$flag =True;
}
if(isset($sponsor)&&$sponsor != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
if($flag){
$cheack.="AND ";
}
$cheack.="workplace = '$address' ";
}