admin管理员组

文章数量:1129441

I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)

$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC   LIMIT ${offset}, ${items_per_page}" );

I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)

$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC   LIMIT ${offset}, ${items_per_page}" );
Share Improve this question edited Dec 23, 2016 at 5:51 Nelson101 asked Dec 23, 2016 at 3:10 Nelson101Nelson101 451 silver badge9 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 1

In your code it is actually counting the query you have inserted in $testargs. In your case you entered one. So it is giving you back one. If you need to get the count on WordPress users table then write the query like below-

global $wpdb;

$total_query = "SELECT COUNT(*) FROM {$wpdb->users} AS total_count";
$total = $wpdb->get_var( $total_query );

i think you code snippet should look something like below code snippet in your code i am not getting why you are adding the same query again in $total_query by appending $testargs so try the below code snippet that should work for you.

$total_query = "SELECT COUNT(*) FROM {$wpdb->users}";
$total = $wpdb->get_var( $total_query );
echo $total;

本文标签: mysqlwpdbgtgetvar not returning count