从数据库返回0时替换提取的结果


Replacing fetched results when returning 0 from DB

当获取数据库时,我会得到结果,一切都可以从数据库中获得价格,这也是有效的,但我真正需要的是,如果price返回的是0,那么"0"应该改为"p.O.D"。

感谢您的帮助。

这是我的查询代码:

 $samples = "SELECT * FROM materials, category_price WHERE materials.type = :cat AND materials.supplier = '$supplier' AND materials.category_id = category_price.category_id";
$res = $db->prepare($samples);
$res->execute(array(':cat' => $category));
$count = $res->rowCount();
if($count > 0)
echo "
<section class='"border mar_t_40'">
"; 
while ($row = $res -> fetch()){
    $postimggranite = $row[image];
    $postidgranite = $row[id];
    $postname = $row[mat_name];
    $folder = $row[type];
    $folder = strtolower($folder);
    $supplier = strtolower($supplier);
    $category_id = $row[category_id];
    $price = ("£ ".$row[price]);

print<<<END
<span class="grid white_back mar_l_30">
<h3>$price</h3>
<a class="fancybox" href="$img_path/$folder/$supplier/large/$postimggranite" rel="group[$postidgranite]" title="$postname"><img alt="$row[name]" src="$img_path/$folder/$supplier/small/$postimggranite" width="100" height="100">$postname</a>
</span>
END;
}
echo "<div class='"clearfloat'"></div></section>";

请参阅此问题。

这就是你要找的表情。

$price = ($row[price] === 0) ? "P.O.D." : ("£ ".$row[price]);

编辑:旁注:我使用=== 0是因为这个问题中描述的问题。

您可以将查询更改为以下内容:

SELECT some_fields, IF(price=0, 'P.O.D', price) AS price FROM materials, category_price WHERE materials.type = :cat AND materials.supplier = '$supplier' AND materials.category_id = category_price.category_id

但是为什么不在PHP中处理这个条件呢?

脑海中浮现出几个想法,其中一个是ternary运算符:

$price = ($row[price] == 0 ? 'P.O.D' : '£ ' . $row[price]);

尝试:

$price = (empty($row[price]) ? "P.O.D" : "£ " . $row[price]);