是否可以将其写为三元运算符?
if($catId){
$clauses[] ='`category` = '.$catId;
}
当我尝试以下内容时,我仍然会得到一个添加到数组中的值
$clauses[] = ($catId)?'`category` = '.$catId:null;
作为参考,我在构建带有 where 子句的 sql 查询时使用它
$where = null;
$clauses = array();
if($manId){
$clauses[] ='`man` = '.$manId;
}
if($catId){
$clauses[] ='`category` = '.$catId;
}
if(count($clauses)){
$where = implode (' && ',$clauses);
$where = 'WHERE '.$where;
}
$sql = "SELECT * FROM `products` $where ORDER BY `isfeatured`,`sortvalue`";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
print $row['name'].'<br>';
}
是的。如果你真的想使用三元,可以这样:
$catId ? $clauses[] = "`category`=$catId" : null;
在这里,赋值发生在三元的真实部分,而不是赋值三元的结果。
但是,使用三元是没有意义的,因为如果变量为空,您不想做任何事情,因此三元的假部分是无关紧要的。应该具有基本相同效果的较短版本是:
$catId && $clauses[] = "`category`=$catId";
就个人而言,我认为您已经拥有它的方式对于以后必须通过不那么奇怪和笨拙来解决这个问题的人来说更具可读性和更友好,但这是可能的。
当然
,您可以按照@Dontpanic的建议使用三元运算符执行此操作。但是你应该更加了解SQL注入,所以我建议使用预准备语句而不是自己替换值,如下所示:
$where = null;
/// Generic query
$sql = "SELECT * FROM `products` WHERE 1 = 1"
$params = array();
if($manId){
$sql .= " AND `man`= ?";
$params[] = $manId;
}
if($catId){
$sql .= " AND `category` = ?"
$params[] = $catId;
}
/// Adding ORDER BY clause
$sql .= " ORDER BY `isfeatured`,`sortvalue`";
/// Prepare query
$stmt = mysqli_prepare ($con, $sql);
foreach($params as $param) {
/// Binding integer parameters
$stmt->bind_param("i", $param);
}
/// Execute the statement
$stmt->execute();
/// Get results
$result = $stmt->get_result();
/// Process the results
while($row = $result->fetch_assoc()){
print $row['name'].'<br>';
}
这看起来不错:
$clauses[] = ($catId)?'`category` = '.$catId:null;
如果$catId不是假的(阅读 PHP 中的强制转换类型),数组中的新 elem 将是一个值等于 ' category
= '.$catId 的字符串,否则为 null,但您总是在这个地方向数组添加新的 elemmt。因此,您的其余代码将无法正常工作。尤其是这部分:
if(count($clauses)){
$where = implode (' && ',$clauses);
$where = 'WHERE '.$where;
}
因为你会得到这样的东西:其中category
= 1 和排序方式