Arjen
Arjen

Reputation: 87

unable to get to count

$query = $db->prepare("SELECT COUNT(id_u) FROM account");
        $query->execute();
        $result = $query->fetch(PDO::FETCH_ASSOC);
        $count = $result['count(id_u)'];
        echo $count;

Not sure what I'm doing wrong here. I'm trying to get it to count the amount of registered users we have by counting the amount of id_u's (user id).

Like I said in the comments, It might be similar to other posts but those don't explain how to fix my situation since they are not quite the same.

Upvotes: 0

Views: 59

Answers (2)

Shohidur Rahman
Shohidur Rahman

Reputation: 68

$count = count($result['id_u']);

Upvotes: 0

Lachie
Lachie

Reputation: 1411

EDIT:

After testing the issue you are experiencing; I managed to solve why your solution is not working. It appears that it is due to you calling COUNT(id_u) in the SQL query, then in the echo statement you are trying to get count(id_u) which doesn't exist in the array. Try

$count = $result;
$count = $result['COUNT(id_u)'];

To detect where the issue is stemming from I'd suggest you add in a print_r($result);. This will give you an idea what is returning from your SQL query in an array format. Once you see what data is returned and available, you can then determine how you echo/print the result.

My opinion on how this should be done:

The use of prepared statements in this is not necessary in my opinion for counting rows.

What I would do is:

$rowCount = $db->query('SELECT COUNT(*) FROM account')->fetchColumn(); 
echo $rowCount;

Upvotes: 1

Related Questions