1

我想“自动”将我的所有数据库数据加载到$db[]和/或$_SESSION['db']. 因此,我只需加载此代码一次,而不是在整个网站上加载零碎。

我能够查询元数据和原始数据,我的问题是创建数组。

假设我有一个temp包含列的表,name并且age我希望能够执行以下操作: -echo $db['temp']['name'] . "'s age is: " . $db['temp']['age'];显然我有很多包含很多列的表。这只是一个例子

<?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);
?>
4

1 回答 1

2

在进入循环之前声明你的数组,然后填充它:

$db = array();

$sql_metadata = 
"SELECT DISTINCT `COLUMNS`.`TABLE_NAME` as 'table' 
FROM `information_schema`.COLUMNS 
WHERE `COLUMNS`.`TABLE_SCHEMA` = '$dbn'";

$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);
    $raw = mysql_fetch_array($dbq2);

    foreach($raw as $value )
    {
        $db[$meta['table']][$meta['column']][] = $value;
    }
}
print_r($db);

解释:您创建一个多维数组,表名指向列名。数组末尾的 [] 告诉 PHP 将 $value 的内容存储到 table=>column 的新数组元素中。

这将是获取整个数据的更简单方法:

    $sql_rawdata = "SELECT * FROM `".$dbn."`.`".$meta['table']."`";
    $dbq2 = mysql_query($sql_rawdata);

    while($raw = mysql_fetch_assoc($dbq2)){
        foreach($raw as $column => $value )
        {
            $db[$meta['table']][$column][] = $value;
        }
    }
于 2012-06-12T05:15:50.910 回答