Reputation: 1027
I'm having a little problem when trying to print certain values from my database. OK so I have a table in my database called site_details
where I save the site name, phone and email. I have a query that returns the following array:
Array
(
[0] => Array
(
[text] => My Store
[0] => My Store
[column_key] => site_name
[1] => site_name
)
[1] => Array
(
[text] => (123) 456 7890
[0] => (123) 456 7890
[column_key] => site_phone
[1] => site_phone
)
[2] => Array
(
[text] => [email protected]
[0] => [email protected]
[column_key] => site_email
[1] => site_email
)
)
I would like to print out the site details using the following code:
//Print out site name
//$site_details is the array being returned from the database
<?php echo $site_details['site_name']; ?>
This returns an
Undefined index: site_name error
. Anyone know how I could go about this? Any help is greatly appreciated.
Update
Here's the code i use to return the site details:
Funtions.php
public function getSiteDetails(){
global $pdo;
$getDetails = $pdo->prepare("
SELECT *
FROM site_details
");
$getDetails->execute();
return $getDetails->fetchAll();
}
This is where I call the function:
index.php
require 'res/php/Functions.php';
$obj = new Functions();
//Get site details
$site_details = $obj->getSiteDetails();
Upvotes: 1
Views: 91
Reputation: 72299
For your given array the printing
mechanism is as follows:-
<?php
foreach($site_details as $site_detail){
echo $site_detail['column_key'].' is:- '.$site_detail['text'];
}
?>
Note:- fetch_assoc
will be better objective.
Also every column value comes separately which shows you did something extra in your code, which is actually not needed
for each value to print:-
<?php echo $site_details[0]['text']; ?>
Upvotes: 1
Reputation: 32
Use $getDetails>fetch(PDO::FETCH_ASSOC)
that gives an array like,
Array
(
[0] => Array
(
[text] => My Store
[column_key] => site_name
)
[1] => Array
(
[text] => (123) 456 7890
[column_key] => site_phone
)
[2] => Array
(
[text] => email@y
[column_key] => site_email
)
)
Then use,
echo $site_details['column_key'];
Upvotes: 0