schmitsz
schmitsz

Reputation: 175

echo PDO query as string in PHP

Basically I am trying to return the total number of columns that correspond to a given criteria:

$exec = $link->query("SELECT COUNT(*) FROM `requests` WHERE language='PHP'");
$result = $exec->fetch(PDO::FETCH_ASSOC);

echo $result[0];

However, the above does not return anything but the SQL query is correct since it returns a value when executed in phpMyAdmin.

Upvotes: 0

Views: 213

Answers (1)

Kevin
Kevin

Reputation: 41875

Since you explicitly used the flag PDO::FETCH_ASSOC, you need to point on the associative index it returns. I'd suggest put an alias on the count()

SELECT COUNT(*) AS total FROM `requests` WHERE language='PHP'

Then access it after fetching:

echo $result['total'];

Another way would be to use ->fetchColumn():

$count = $exec->fetchColumn();
echo $count;

Upvotes: 3

Related Questions