Wordpress $ wpdb-> get_results和num_rows

时间:2012-11-05 16:10:34

标签: wordpress wpdb

我使用以下代码:

                    $wpdb->get_results("
                        SELECT * FROM " . $wpdb->prefix . "product_order 
                            WHERE 
                            rel = '" . $post["id"] . "' AND 
                            `range` = '" . $range . "' AND 
                            category = '" . $range . "'
                    "); 

                    echo $wpdb->num_rows;

num_rows返回1,即使数据库中没有行? 有什么想法吗?

我投入的变量看起来很好。所以它应该正确查询。

2 个答案:

答案 0 :(得分:8)

global $wpdb;
$wpdb->get_results("
                    SELECT * FROM " . $wpdb->prefix . "product_order 
                        WHERE 
                        rel = '" . $post["id"] . "' AND 
                        `range` = '" . $range . "' AND 
                        category = '" . $range . "'
                "); 

echo $wpdb->num_rows;

现在它返回从上面的查询中选择的行数,如果没有选择行则返回0 .....

答案 1 :(得分:1)

如果只需要计数(也许是总分页数),则执行速度更快:

global $wpdb;
$rows = $wpdb->get_results("
                    SELECT COUNT(*) as num_rows FROM " . $wpdb->prefix . "product_order 
                        WHERE 
                        rel = '" . $post["id"] . "' AND 
                        `range` = '" . $range . "' AND 
                        category = '" . $range . "'
                "); 

echo $rows[0]->num_rows;