markerpower
markerpower

Reputation: 345

How to print array?

I'm trying to learn how to print results from a query, but I'm getting confused.

Config Table:

site_id | site_name | site_description

1         Test        Testing

Config:

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(); 
}

Code #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'];
}

This prints nothing.

Code #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;
}

This prints the info, but is it the correct approach? Is there a way to print with Code #1?

All I want to do is echo site name. There is only one site name.

Upvotes: 1

Views: 120

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Without more info about your config table design the only think I can suggest is something like that:

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

NAME_COLUMN_NAME and VALUE_COLUMN_NAME have to be replaced with column names from your table design.

After that you'll be able to get custom config parameter from $this->site_info array by it's name, eg.

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

Upvotes: 1

Cal
Cal

Reputation: 7157

In example #1, $this->site_info contains an array of arrays. To simply see the contents:

print_r($this->site_info);

To loop over the contents, printing the names of each row:

foreach ($this->site_info as $row){
   echo $row['site_name'];
}

Upvotes: 0

Related Questions