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.
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;
?>
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With