Home  >  Article  >  Backend Development  >  sql中对于传过来的空值判断,该怎么处理

sql中对于传过来的空值判断,该怎么处理

WBOY
WBOYOriginal
2016-06-13 13:13:39816browse

sql中对于传过来的空值判断
我有四个这样的输入值
action到处理的php页面
有没有什么方法能够合理的让php页面的sql语句判断当那个字段为空时,就不以那个为搜索的条件了
除了穷举,还有什么方法?
$sql="select * from table where ..."


实例:
html


姓名:
年龄:
性别:
身高:


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);
<br><font color="#e78608">------解决方案--------------------</font><br>应该是,上面少给一个''<br><br>
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]'"; <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn