日期:2014-05-17  浏览次数:20537 次

sql中对于传过来的空值判断
我有四个<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?

------解决方案--------------------
PHP code
foreach(array_diff($_POST, array('')) as $k=>$v)
  $r[] = "$k='$v'";

$sql = "select * from student where ". join(' and ', $r);

------解决方案--------------------
应该是,上面少给一个''

PHP code
$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]'";