我有四个<input type="text" name=""/>这样的输入值
action到处理的php页面
有没有什么方法能够合理的让php页面的sql语句判断当那个字段为空时,就不以那个为搜索的条件了
除了穷举,还有什么方法?
$sql="select * from table where ..."
实例:
html
<form action="chuli.php" method="post">
姓名:<input type="text" name="name">
年龄:  <input type="text" name="age">
性别:  <input type="text" name="sex">
身高:  <input type="text" name="height">
</form>chuli.php
//连接数据库部分省略
$sql="select * from student where name='$name' and age='$age' and sex='$sex' and height='$height';// 这个是所有的  
$result = mysql_query($sql,$con);//除了穷举以外,有没有什么方法,判断那几个Input数据为空的时候的$sql进行判断的方法?
//如果是4个input的情况下的时候是 4+6+4+1+1=16种情况,应该对吧? c41+c42+c43+c44+1=4+6+4+1+1=16?

解决方案 »

  1.   

    foreach(array_diff($_POST, array('')) as $k=>$v)
      $r[] = "$k='$v'";$sql = "select * from student where ". join(' and ', $r);
      

  2.   

    $where = '1=1';
    if($_POST['name'] != ''){
        $where .= " and name= ‘".$_POST['name']."'";
    }
    if($_POST['age'] != ''){
        $where .= " and age= ‘".$_POST['age']."'";
    }
    if($_POST['sex'] != ''){
        $where .= " and sex= ‘".$_POST['sex']."'";
    }
    if($_POST['height'] != ''){
        $where .= " and height= ‘".$_POST['height']."'";
    }
    $sql="select * from student where". $where
      

  3.   


    $sql="select * from student where 1=1";
    if(!empty($_POST['name'])) $sql=" and name=$_POST[name]'";
    if(!empty($_POST['age'])) $sql=" and age=$_POST[age]'";
    if(!empty($_POST['sex'])) $sql=" and sex=$_POST[sex]'";
    if(!empty($_POST['height'])) $sql=" and height=$_POST[height]'";
      

  4.   

    应该是,上面少给一个''$sql="select * from student where 1=1";
    if(!empty($_POST['name'])) $sql=" and name='$_POST[name]'";
    if(!empty($_POST['age'])) $sql=" and age='$_POST[age]'";
    if(!empty($_POST['sex'])) $sql=" and sex='$_POST[sex]'";
    if(!empty($_POST['height'])) $sql=" and height='$_POST[height]'";
      

  5.   

    2楼同学的方案是可行的、使用 where 1 = 1 进行sql语句动态拼接、