echo PDO query as string in PHP

schmitsz

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.

Kevin

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;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related