Rowan Richie
Rowan Richie

Reputation: 3

Echo count from data in a database

I am trying to count a specific field in a database that has user details in it. Every user has an id and I want to count the amount of users/ids that are registered in the database. This is my code, how can I solve it? Because it does not echo anything. I am not allowed to use MYSQL to retrieve the count.

include ("databaseconnectie.php");
$query = $db->prepare("
    SELECT 
        COUNT(id) as total 
    FROM 
        users");

$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);

echo $result['total'];`

Upvotes: 0

Views: 100

Answers (1)

Lachie
Lachie

Reputation: 1411

Due to the way you fetch'ed your data, you will need to add [0] in the $result echo. ($result[0]['total']).

I added in a print_r($result) to show me the array so I could identify where the issue came from and how I can step through the array to get my intended result.

$query = $db->prepare("SELECT COUNT(id) as total FROM users");
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
echo $result[0]['total'];

EDIT:

As mentioned by @Federkun; you could change this line:

$result = $query->fetchAll(PDO::FETCH_ASSOC);

to:

$result = $query->fetch(PDO::FETCH_ASSOC);

Then you wouldn't need to add the [0] as it is just fetching one result.

Upvotes: 2

Related Questions