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

Hi I am new in PHP developing and i am trying to make a search in a website and would like to have several search terms which is input by the user to perform db search, terms as below:

  • Sex

  • Status

  • State

  • Country

    Here is script to perform search with above term's input:

    $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))
      {
    

I suspect that you will have errors in your logs relating to undeclared constants - the $_REQUEST variables require the variable name to be quoted - unless they are actually declared as constants.. so they should look more like:-

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

The where clauses need quotes around the values as they appear to be strings.. so:-

$where[] = 'm_ton = "' . addslashes($m_ton) . '"';
and
$where[] = 'user_sex = "' . addslashes($user_sex) . '"';