Wordpress $wpdb->get_results and num_rows

落花浮王杯 提交于 2020-03-18 09:10:41

问题


I'm using the following code:

                    $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 returns 1 even though there is no rows in the database? Any ideas?

The variables I am putting in look fine. so it should be querying correctly.


回答1:


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;

Now it returns numbers of rows select from above query and 0 if no row selected.....




回答2:


if you JUST want the count (maybe for pagination total), it is faster to do:

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;


来源:https://stackoverflow.com/questions/13235947/wordpress-wpdb-get-results-and-num-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!