How to count number of records in a table?

Asked

Viewed 2,360 times

4

I have a call table noticias, where every news has a id. I also have a table called comentarios, where there is the id of the news the user commented on. How can I count the comments for that news?

  • Show how the table structure looks like. Probably what you need is just SQL for the count itself.

  • 1

    select count(id_comentario) from comentarios where id_noticia = ?

  • I did so: $counter = mysql_query("SELECT Count(id) FROM 10cms_noticias_resp WHERE id_noticia = id_noticia") or die(mysql_error(); . So I can pull the number of news comments I’m what I do?

  • @Kloves Wouldn’t it be better to put the field name fk, since it is a foreign key? In fact, this relationship is that one news has several comments. Soon the id of each news goes to the foreign key of each comment. ) or die(mysql_error());

2 answers

1


You can do it this way, it’s good to add an alias(name) to the count so it’s easy to remember the field name in php.

$contador = mysql_query("SELECT count(id) as total FROM 10cms_noticias_resp 
                         WHERE id_noticia = id_noticia") or die(mysql_error());

$comentario = mysql_fetch_assoc($contador);
echo $comentario['total'];
  • This total is from the Count function?

  • total is the name of the column returned by the query, sql has changed a little SELECT count(id) as total o have defined the name. @Kloves

  • There’s nothing on the echo.

  • make a print_r($comentario) see if anything pops up, @Kloves

  • Where I put the print_r?

  • after echo. @kloves

  • Appeared: Array ( [total] => 1 ). How can I put to appear only 1?

  • just do echo $comentario['total'];.

Show 4 more comments

1

A simple query by id, already solves:

SELECT COUNT(*) AS total_comentarios FROM comentarios where id_noticia=:id

Browser other questions tagged

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