PHP PDO Not counting above 9?

I have a simple counting algorithm in PHP using PDO and MySQL. The problem is that the code doesn’t count past 9.

I have table with 99 records inside. Here is the code:

<p>Number of Excused Absences:
<b style="color: #000000;">
$stmt = $pdo->prepare("SELECT COUNT(member_id) FROM absence WHERE absent = 1;");				  $stmt->execute();
$result = implode($stmt->fetch());
$absent =  $result[0];
echo $absent;

When I run the query in phpMyAdmin, it comes out to 99. But in the site itself, it only shows 9. What did I do wrong?



Why are you using implode? Get rid of it. Additionally, You are preparing the query but not using a prepared statement.

This is all you need.

$stmt = $pdo->prepare("SELECT COUNT(member_id) count FROM absence WHERE absent = ?");
$result =$stmt->fetch();
echo $result['count'];
1 Like

That did the trick. Thanks!

I think what you’ve run in to there is that PHP treats strings as arrays, even if they’re not arrays. So when you

$absent = $result[0];

you actually take the first character of the string which is $result, in this case a 9. $result isn’t an array, because it’s the result of your implode() call. So you’re getting a character from a string, not an element of an array.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.