1

我在使用 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 语句工作。

4

2 回答 2

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.

于 2013-03-24T12:25:19.663 回答
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' ";
}
于 2013-03-24T12:29:36.163 回答