如果没有结果,Get_num_rows无法正确显示

时间:2015-06-27 13:38:22

标签: php sql wordpress

我有一个工作查询,可以在我的数据库和前端成功显示正确的行。目前我的PHP代码是:

$rows = $result->num_rows;
if($rows>=0){
  foreach ($result as $row) {
    echo '<h5 style="background-color:yellow;width:60%"><i>'.$row->company.'</i> can perform your window installation for <i>$'.ROUND($row->newcost,2).'</i><br>';
    echo 'This price includes using <i>'.$row->material.'</i> as your material(s)<br>';
    echo '<hr></h5>';
  }
}else{echo 'No results found';}

即使在原始查询中找到了两行,它也会显示“未找到结果”&#39;只有在没有结果的情况下才会发出消息......基本上它与我想要的方式相反。

同样$result是我为查询命名的变量。 有人可以让我了解我可能做错了吗?

编辑我正在使用的查询是:

$result = $wpdb->get_results( "SELECT `b`.`company` AS `company`,`bp`.`material` AS `material`,
if(((`bp`.`cost` * 1.2) < `ls`.`maximumbid`),(ROUND(`bp`.`cost` * 1.2,2)),ROUND(`bp`.`cost`,2)) AS `newcost` 
from (((`doors_brands_products` `bp` left join `doors_brands` `b` on((`bp`.`brand_id` = `b`.`id`))) 
join `Doors_last_submissions` `ls`) join `doors_materials` `wm`) 
where ((`bp`.`width` = round(`ls`.`width`,0)) 
and (`bp`.`height` = round(`ls`.`height`,0)) 
and (`bp`.`material` = `wm`.`name`) 
and (`bp`.`type` = `ls`.`type`) 
and if((`ls`.`minimumbid` <> '0.00'),(`bp`.`cost` between `ls`.`minimumbid` and `ls`.`maximumbid`),(`bp`.`cost` <= `ls`.`maximumbid`)))
ORDER BY b.company ASC");

2 个答案:

答案 0 :(得分:1)

这并不是说你不能在返回数组的查询中使用num_rows ...虽然这也可以正常工作

答案 1 :(得分:0)

根据WP文档,get_results方法默认返回对象数组。 (https://codex.wordpress.org/Class_Reference/wpdb

数组没有num_rows属性。只需尝试将代码更改为:

$rows = $result ? count($result) : 0;
if($rows>=0){
    foreach ($result as $row) {
        echo '<h5 style="background-color:yellow;width:60%"><i>'.$row->company.'</i> can perform your window installation for <i>$'.ROUND($row->newcost,2).'</i><br>';
        echo 'This price includes using <i>'.$row->material.'</i> as your material(s)<br>';
        echo '<hr></h5>';
    }
}else{echo 'No results found';}