Reputation:
I am using PDO and trying to display how many users are in a table, however I get this error:
Notice: Array to string conversion in C:\Users\admin.phtml on line 10 Array
Then in my Admin class:
public function CountUsers()
{
$query = "SELECT * FROM Users";
$statement = $this->_dbHandle->prepare($query);
// Then execute the query
$statement->execute();
// This will return the row from the database as an array
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
Then in my Admin Controller I have:
$Admin = new Admin();
$CountUsers = $Admin->CountUsers();
To display the results I have this in my phtml:
<var><?php echo $CountUsers; ?></var>
Does anyone understand what I am doing wrong?
Upvotes: 2
Views: 1360
Reputation: 1436
You should try to count the users in query, like so:
public function CountUsers() {
$query = "SELECT COUNT(1) FROM Users";
$statement = $this->_dbHandle->prepare($query);
if($statement->execute()) {
// This will return COUNT(1) field
return $statement->fetch(PDO::FETCH_NUM)[0];
}else{
return 0; // should the query fail, return 0
}
}
If you want to stick to counting in PHP (which you shouldn't), modify your code to do:
return count($statement->fetchAll(PDO::FETCH_ASSOC));
But you shouldn't query all of the data just to count and discard it. Using SQL's count
is far more performant for several reasons:
fetchAll
, it will store all of the data into PHP array, taking up memoryTo display a meaningful text, or do something with this function you can:
function CheckUsers() {
$userCount = CountUsers();
if($userCount == 0) {
echo 'No users found';
}else{
echo $userCount . ' users found';
}
}
Upvotes: 2