php - 带有2个参数的函数内的mysql查询

标签 php mysql

我的功能是这样

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;
}

因此,每当我尝试使用此函数从数据库获取数据时,即使只有 $where 和 $condition 为 true,而 $where2 和 $condition2 为 false,它也会返回行。

最佳答案

您可以支持可变长度的条件。

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);
}

但是,所有 mysql_* 函数均已已弃用。我强烈建议您迁移到 PDOmysqli

关于php - 带有2个参数的函数内的mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319743/

相关文章:

javascript - 如何使Excel文件成为交互式网页?

mysql用同一个表中的多个值更新表列

javascript - 如何使用 php 和 mysql 验证单选按钮?

php - 选择与特定日期重叠的日期范围

php - Mysql 从 table1 中选择,其中 row1 等于 table2 中的 row1 在 php 中?

PHP include() 替代方案?

php - 使用 php-jquery 替换图像时出现问题

python - 如何扩展 django 用户默认模型数据库

php - 计算某些网址的浏览量

php - 使用 PHP 数组分配随机 CSS 伪类