1

我正在尝试学习如何从查询中打印结果,但我很困惑。

配置表:

site_id | site_name | site_description

1         Test        Testing

配置:

private $hostname = 'localhost';
private $username = 'blah';
private $password = 'blah';
private $database = 'blah';

public function __construct()
{
    $this->connection = new mysqli($this->hostname,$this->username,$this->password,$this->database);

    if($this->connection->connect_errno) 
    {
        die('Error: ' . $this->connection->error);
    }
}

public function query($query)
{
    return $this->connection->query($query);
}

public function __destruct()
{
    $this->connection->close(); 
}

代码#1:

public function __construct()
{
    $this->db = new Config;

    $si = $this->db->query('SELECT * FROM config');

    while($site_if = $si->fetch_array())
    {
        $this->site_info[] = $site_if;
    }

}

public function getSiteName()
{
    echo $this->site_info['site_name'];
}

这不打印任何内容。

代码#2:

public function __construct()
{
    $this->db = new Config;

    $si = $this->db->query('SELECT * FROM config');

    while($site_if = $si->fetch_array())
    {
        $this->site_name_info = $site_if['site_name'];
    }

}

public function getSiteName()
{
    echo $this->site_name_info;
}

这会打印信息,但这是正确的方法吗?有没有办法用代码 #1 打印?

我想做的就是回显站点名称。只有一个站点名称。

4

2 回答 2

1

如果没有有关您的配置表设计的更多信息,我唯一可以建议的想法是:

while($site_if = $si->fetch_array())
{
    $this->site_info[$site_if["NAME_COLUMN_NAME"]] = $site_if["VALUE_COLUMN_NAME"];
}

NAME_COLUMN_NAME并且VALUE_COLUMN_NAME必须用表格设计中的列名替换。

之后,您将能够$this->site_info通过其名称从数组中获取自定义配置参数,例如。

public function getSiteName()
{
    echo $this->site_info['site_name'];
}
于 2012-04-08T19:55:59.267 回答
0

在示例 #1 中,$this->site_info包含一个数组数组。简单查看内容:

print_r($this->site_info);

要遍历内容,打印每一行的名称:

foreach ($this->site_info as $row){
   echo $row['site_name'];
}
于 2012-04-08T19:54:42.883 回答