admin管理员组

文章数量:1389768

I am new to wordpress development & tried to learning plugin development.I have created a custom table from which i want to show the number of records found.I have tried the below code but it always shows 1 as a result irrespective of number of rows in a table.

//To show number of rows in table
    function DB_Tables_Rows()
    {
      global $wpdb;
      $table_name = $wpdb->prefix . 'mydata';
     $count_query = "select count(*) from $table_name";
         $num = $wpdb->get_var($count_query);

         $num = $wpdb->num_rows;

        echo  $wpdb->num_rows . 'Rows Found';


    }

I am new to wordpress development & tried to learning plugin development.I have created a custom table from which i want to show the number of records found.I have tried the below code but it always shows 1 as a result irrespective of number of rows in a table.

//To show number of rows in table
    function DB_Tables_Rows()
    {
      global $wpdb;
      $table_name = $wpdb->prefix . 'mydata';
     $count_query = "select count(*) from $table_name";
         $num = $wpdb->get_var($count_query);

         $num = $wpdb->num_rows;

        echo  $wpdb->num_rows . 'Rows Found';


    }
Share Improve this question asked Dec 8, 2014 at 6:44 hiteshhitesh 231 gold badge1 silver badge3 bronze badges 1
  • get_var already returns count. Check dumping $num variable. – Nilambar Sharma Commented Dec 8, 2014 at 11:15
Add a comment  | 

2 Answers 2

Reset to default 6

Why don't you directly echo the $num as it will contain the count of rows already...Here's the edited part..

//To show number of rows in table
  function DB_Tables_Rows()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'mydata';
    $count_query = "select count(*) from $table_name";
    $num = $wpdb->get_var($count_query);

    echo  $num . 'Rows Found';


}

WAY #1

You can use the WordPress way using $wpdb class:

<?php
global $wpdb;
$table_name = $wpdb->prefix . 'mydata';
$my_query = $wpdb->get_results( "SELECT * FROM $table_name" );
echo $my_query->num_rows;

The codex says:

Since this function uses the $wpdb->query() function all the class variables are properly set. The results count for a 'SELECT' query will be stored in $wpdb->num_rows.

WAY #2

It can also be count by PHP way. Just use your generic query, and use the PHP count() function.

<?php
global $wpdb;
$table_name = $wpdb->prefix . 'mydata';
$my_query = $wpdb->get_results( "SELECT * FROM $table_name" );
$num_rows = count( $my_query ); //PHP count()
echo $num_rows;

Reference: http://php/manual/en/function.count.php

Though it's my favorite, but as @MarkKaplun says:

there is a huge performance difference between counting the size of an array in PHP, and letting mysql count the rows for you. You are unlikely to notice it on small data, but for big tables you will.

So I'd also love to stick with the $wpdb way. <3

本文标签: pluginsHow to count number of records found in a database table