我的功能是这样
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_*
函数均已已弃用。我强烈建议您迁移到 PDO
或 mysqli
。
关于php - 带有2个参数的函数内的mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319743/