How to return an array and only show the count number

Asked

Viewed 50 times

0

I made this code so that a count of the number of comments was performed, and returned the value of how many comments there were in the post. But instead of just returning the value, it’s returning this:

Array ( [COUNT(*)] => 9 ) //Commentary

How do I return only the 9 instead of Array ( [COUNT(*)] => 9 ) ?

<?php
    $query = mysql_query("SELECT COUNT(*) FROM comentario");
    $linhas = mysql_fetch_assoc($query);
?>

<h4 class="mb-30"><?php print_r ($linhas); ?> Comentários</h4>

2 answers

0

Can use AS to make COUNT an easier nickname and would look like this:

<?php
    $query = mysql_query("SELECT COUNT(*) as total FROM comentario");
    $linhas = mysql_fetch_assoc($query);
?>

<h4 class="mb-30"><?php echo $linhas['total']; ?> Comentários</h4>

Note that you should urgently change the mysql connection API frommysql_ to MYSQLI or PDO, I recommend you read:

  • Thank you!! It worked

  • @Athena benefits from starting and not using the old php api for mysql, it has been removed in PHP7 and its codes will fail in this version, switch to the more modern API like mysqli or PDO, read more on: https://answall.com/q/579/3635 --- PS: the database remains mysql, only the communication API has changed ;)

0

I believe you’re learning to program with language , because these functions are already depreciated and no one else uses, but, answering basically put a alias (AS) in his and how will one be returned array associative makes it easy to work on your presentation code:

<?php
    $query = mysql_query("SELECT COUNT(*) as count FROM comentario");
    $linhas = mysql_fetch_assoc($query);
?>

<h4 class="mb-30"><?php echo $linhas['count']; ?> Comentários</h4>

and change print_r for echo.


Utilize PDO or if it’s the database MySQL the Mysqli which are more current and are always being updated, but this does not change the SQL that is in your question is the same thing. If you want to deepen use this reply as one of the sources, in the php.net which is the official website also has enough material

  • 1

    yes I’m learning really, thank you very much, it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.