Whats the best way to get total # of records in a mysql table with php?

后端 未结 10 521
后悔当初
后悔当初 2021-01-12 05:51

Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing

$result = mysql_query(\"SELECT id FROM table         


        
相关标签:
10条回答
  • 2021-01-12 05:59

    mysqli_query() is deprecated. Better use this:

    $result = $dbh->query("SELECT id FROM {table_name}");
    $total = $result->num_rows;
    

    Using PDO:

    $result = $dbh->query("SELECT id FROM {table_name}");
    $total = $result->rowCount();
    

    (where '$dbh' = handle of the db connected to)

    0 讨论(0)
  • 2021-01-12 06:00

    MyISAM tables already store the row count

    SELECT COUNT(*) FROM table
    

    on a MyISAM table simply reads that value. It doesn't scan the table or the index(es). So, it's just as fast or faster than reading the value from a different table.

    0 讨论(0)
  • 2021-01-12 06:01

    According to the MySQL documentation this is most efficient if you're using a MyISAM table (which is the most usual type of tables used):

    $result = mysql_query("SELECT COUNT(*) FROM table");
    

    Otherwise you should do as Wayne stated and be sure that the counted column is indexed.

    0 讨论(0)
  • 2021-01-12 06:01

    Just wanted to note that SHOW TABLE STATUS returns a Rows column, though I can't speak to its efficiency. Some light Googling turns up reports of slowness in MySQL 4 over two years ago. Might make for interesting time trials.

    Also note the InnoDB caveat regarding inaccurate counts.

    0 讨论(0)
  • 2021-01-12 06:03

    You were told correctly. mysql can do this count for you which is much more efficient.

    $result = mysql_query( "select count(id) as num_rows from table" );
    $row = mysql_fetch_object( $result );
    $total = $row->num_rows;
    
    0 讨论(0)
  • 2021-01-12 06:06

    Use aggregate function. Try the below SQL Command

    $num= mysql_query("SELECT COUNT(id) FROM $table");
    
    0 讨论(0)
提交回复
热议问题