I have 6 mysql tables in my database.
and each table contains column 'amount'
I want sum of all amounts in all tables.
But getting error as
Invalid argument supplied for foreach() in // foreach ($tablenames as $tablename) {
and
undefined variable query
Code is as follows :
I want specific tables from my database and more tables will be added per year which will contain amount
column. So I extracted table names first.
$tablenamearray = array(); $tablenamequery = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'databasename' and table_name LIKE '%registration%'"; $tablenameres = $database->get_results($tablenamequery); foreach ($tablenameres as $tablenamedata){ $tablenamearray[]=$tablenamedata['table_name']; } $tablenamearray_final = "'".join("', '",$tablenamearray)."'"; $tablenamesrcvd = "array(".$tablenamearray_final.");"; ///$tablenamesrcvd are as given below when I echo // array('table_1','table_2','table_3','table_4','table_5','table_6'); foreach ($tablenamesrcvd as $tablename) { $query = "select SUM(`amount`) as Total from $tablename"; $res = $database->get_results($query); // using wrapper class foreach ($res as $data){ $totalrcvd = $data['Total']; } }
What I am missing ?
Advertisement
Answer
$tablenamesrcvd
is a string, not an array.
The variable $tablenamearray
contains the array of table names, you can loop over that. You don’t need to convert it to a string.
You should also add to $totalrcvd
, not reassign it each time through the loop, using +=
instead of =
.
$totalrcvd = 0; foreach ($tablenamesarray as $tablename) { $query = "select SUM(`amount`) as Total from $tablename"; $res = $database->get_results($query); // using wrapper class foreach ($res as $data){ $totalrcvd += $data['Total']; } } echo $totalrcvd;