Reputation:
So I have this code to count the number of 'Guides' by counting the number of IDs on the table.
function getGuideCount() {
global $db;
$query = $db->query("SELECT COUNT(id) AS count FROM kk_hq_guides ");
$fetch = $query->fetchAll(PDO::FETCH_ASSOC);
return $fetch;
}
I am returning the value to a vardump and I am getting this:
array(1) { [0]=> array(1) { ["count"]=> string(2) "36" } } Array
This is correct, I have an array with the key 'Count' storing the amount of guides.
Problem comes when I try to print that value.
$guideCount=getGuideCount();
print($guideCount['count']);
results in the following error:
Notice: Undefined index: count in ... on line 130. (Line 130 is this: return $fetch; )
Big thanks in advance!
Upvotes: 0
Views: 329
Reputation: 164813
First, globals are truly awful. Instead, pass dependencies in where required.
Second, your query will only ever return one row with one column so fetchAll
is superfluous.
Try this instead...
function getGuideCount(PDO $db) {
$query = $db->query("SELECT COUNT(id) FROM kk_hq_guides ");
return $query->fetchColumn();
}
then...
$guideCount = getGuideCount($db);
echo $guideCount;
Upvotes: 0
Reputation: 746
$guideCount[0]['count']
The first item in the $guideCount
array is an array containing one element with a key of 'count'.
Upvotes: 1