0

well my function is this

function all_products($where, $condition, $where2, $condition2) {
    $query = "SELECT *
              FROM `product` 
              WHERE 
              ".mysql_real_escape_string($where)." = '".mysql_real_escape_string($condition)."'  
              and  
              ".mysql_real_escape_string($where)." = '".mysql_real_escape_string($condition)."' 
              ";
    $query_run = mysql_query($query);
    return $query_run;
}

so whenever Im trying to use this function to fetch the data from db it returns rows even if only the $where and $condition is true and $where2 and $condition2 is false.

  • Check your second condition should be: `".mysql_real_escape_string($where2)." = '".mysql_real_escape_string($condition2)."'` -- You are also vulnerable to SQL injection attacks. See: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php –  Jan 23 '14 at 21:36

1 Answers1

0

You can support variable length of conditions.

function all_products(array $assoc) {
    foreach ($assoc as $key => $value) {
        $pairs[] = sprintf(
            "`%s` = '%s'",
            addcslashes($key, '`'),
            mysql_real_escape_string($value)
        );
    }
    $sql = empty($pairs) ?
           'SELECT NULL LIMIT 0' :
           'SELECT * FROM `product` WHERE ' . implode(' AND ', $pairs);
    return mysql_query($sql);
}

However, all mysql_* functions are already DEPRECATED. I strongly recommend you migrate to PDO or mysqli.

mpyw
  • 5,526
  • 4
  • 30
  • 36