I want to “automatically” load ALL my database data into $db[] and/or $_SESSION['db']. Thus, I just have to load this code once, instead of loading bits and pieces throughout the website.
I was able to query the meta data and raw data, my problem is creating the array.
Let’s say I have a table temp with columns name and age I want to be able to do something like this: echo $db['temp']['name'] . "'s age is: " . $db['temp']['age']; -Obviously I have lots of tables with lots of columns. This is just an example
<?php
$dbn = "db_name";
$dbu = "db_user";
$dbp = "db_password";
$hst = 'db_host';
$dbc = mysql_connect($hst,$dbu,$dbp);
$sql_metadata =
"SELECT `COLUMNS`.`TABLE_NAME` as 'table' , `COLUMNS`.`COLUMN_NAME` as 'column'
FROM `information_schema`.COLUMNS
WHERE `COLUMNS`.`TABLE_SCHEMA` = '$dbn'
ORDER BY TABLE_NAME ASC , `COLUMNS`.`COLUMN_NAME` ASC";
$dbq = mysql_query($sql_metadata, $dbc);
while( $meta = mysql_fetch_array($dbq) )
{
$sql_rawdata = "SELECT `$meta['column']` FROM `$dbn`.`$meta['table']`";
$dbq2 = mysql_query($sql_rawdata);
foreach( ($raw = mysql_fetch_array($dbq2)) as $value) )
{
$db = array
(
$meta['table'] => array( $meta['column'] => $value)
);
}
}
print_r($db);
?>
Declare your array before going into the loop and then fill it:
For explanation: You create a multi-dimensional array with the table name pointing towards the column names. the [] at the end of the array tells PHP to store the content of $value into a new array element of table=>column.
THis would be an easier way to fetch the whole data: