Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total number of rows in a MySQL database?

Tags:

sql

php

mysql

I have many tables in my MYSQL database. I want to be able to echo the total number of all the rows in a database.

So basically I want to have it so the circled sum in the image below is echoed in PHP. enter image description here

This is my current code for just displaying the total rows from one table ($txid). I have tried replaced $txid with * but it doesnt work. Any help is greatly appreciated. Thanks.

mysql_select_db($dbname);

$result = mysql_query("select count(1) FROM $txid");
$row = mysql_fetch_array($result);

$total = $row[0];
echo $total;

?>
like image 535
user3462992 Avatar asked Dec 20 '22 16:12

user3462992


2 Answers

Use the schema:

SELECT SUM(TABLE_ROWS) 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA = '{DB_NAME}'

That is what phpmyadmin is using.

Source: Get record counts for all tables in MySQL database

like image 159
Aziz Saleh Avatar answered Dec 24 '22 00:12

Aziz Saleh


There is no way to "wildcard" across multiple tables - this is one reason why normalized [row-oriented] designs are good.

Instead, the query (or queries) must be written in such a way that that all the tables are specified manually - that is, there is a separate SELECT per table. These can then be grouped with UNION ALL and SUM'ed, or summed in PHP after running each query individually.

select SUM(i) as total
from (
  select count(*) as i FROM tx
  union all
  select count(*) as i FROM tx2
  -- repeated for each table
) counts

(The SQL can be generated dynamically in PHP or in MySQL from a list of the tables to query.)

If you only need a rough estimate, then the INFORMATION_SCHEMA TABLES.TABLE_ROWS table can be queried - and indeed this presents a row-oriented design. However, at least for InnoDB tables, this is not guaranteed to return the same results as a direct COUNT.

For InnoDB tables, the row count is only a rough estimate used in SQL optimization.

like image 24
user2864740 Avatar answered Dec 24 '22 02:12

user2864740