用于使用mysql搜索多个条件的SQL查询

时间:2016-07-24 09:10:42

标签: php mysql sql

您好我是PHP开发的新手,我正在尝试在网站上进行搜索,并希望有几个搜索字词由用户输入以执行数据库搜索,条款如下:

  • 状态

  • 国家

  • 国家

    以下是使用上述术语输入执行搜索的脚本:

    $m_ton=$_REQUEST[m_ton];
    $user_sex=$_REQUEST[user_sex];
    $user_status=$_REQUEST[user_status];
    $user_country=$_REQUEST[user_country];
    $user_state=$_REQUEST[user_state];
    $user_city=$_REQUEST[user_city];
    $religion=$_REQUEST[religion];
    $age=$_REQUEST[age];
    
    $sql = 'SELECT * FROM table WHERE ';
    $where = array();
    
    if (!empty($m_ton)) {
        $where[] = 'm_ton = ' . addslashes($m_ton) . '';
    }
    
    if (!empty($user_sex)) {
        $where[] = 'user_sex = "' . addslashes($user_sex) . '';
    }
    $sql .= implode(' AND ',$where);
    
         $rs=mysql_query($sql) or die(mysql_error());
      while($data=mysql_fetch_assoc($rs))
      {
    

1 个答案:

答案 0 :(得分:0)

我怀疑你的日志中会有与未声明的常量相关的错误 - $_REQUEST变量需要引用变量名 - 除非它们实际上被声明为常量..所以它们看起来应该更像:

$m_ton=$_REQUEST['m_ton'];
$user_sex=$_REQUEST['user_sex'];
$user_status=$_REQUEST['user_status'];
$user_country=$_REQUEST['user_country'];
$user_state=$_REQUEST['user_state'];
$user_city=$_REQUEST['user_city'];
$religion=$_REQUEST['religion'];
$age=$_REQUEST['age'];

where子句需要在值周围引用,因为它们看起来像是字符串..所以: -

$where[] = 'm_ton = "' . addslashes($m_ton) . '"';
and
$where[] = 'user_sex = "' . addslashes($user_sex) . '"';
相关问题