Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress $wpdb->get_results and num_rows

Tags:

wordpress

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.

like image 340
Jimmyt1988 Avatar asked Nov 05 '12 16:11

Jimmyt1988


2 Answers

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.....

like image 52
Raman Singh Avatar answered Oct 16 '22 21:10

Raman Singh


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;
like image 25
Scotty G Avatar answered Oct 16 '22 20:10

Scotty G