This question already has answers here:
Combination of field search using PHP & MYSQL
                                
                                    (3个答案)
                                
                        
                                5年前关闭。
            
                    
我在数据库中有一个表,其列名称为:

Name
Department
organization
location
year
email


我有一个具有3个名称属性值的表单:departmentyearorganization

当用户填充任何这些属性时,我希望将其发布到我的PHP脚本中,然后该脚本将仅基于填充的属性来查询结果。

例如:


情况1:填写的表格数据是部门和公司,年份保留为空
情况2:根据填写的数据,公司和年份部门为空,并且这种情况。


如何修改下面的查询脚本,以便获得所需的结果?

// Conneced to server and select database.

$sql="SELECT * FROM $tbl_name WHERE dept =$_post['dept'] and year =$_post['year'] and company  =$_post['commpany'];
$result = mysql_query($sql);
while($rows=mysql_fetch_array($result)) {
?>

最佳答案

你应该在哪里使用动态

$where = "WHERE 1 ";

if(isset($_POST['dept']) && $_POST['dept']!="")
{
      $dept = mysql_real_escape_string($_POST['dept']);
      $where .= " AND dept='$dept' ";
}

if(isset($_POST['year']) && $_POST['year']!="")
{
      $year = mysql_real_escape_string($_POST['year']);
      $where .= " AND year='$year' ";
}

if(isset($_POST['commpany']) && $_POST['commpany']!="")
{
      $commpany = mysql_real_escape_string($_POST['commpany']);
      $where .= " AND commpany='$commpany' ";
}

$sql="SELECT * FROM `$tbl_name` ".$where;


注意:不建议使用mysql_*mysqli_*

10-05 20:51
查看更多