0

All I need to do, is count all fields of the table, where postid=38.

But my code always prints "1" on screen, no matter what number I write in postid=38.

<? 
    $consulta2 = mysql_query("select count(*) from $tabla_db4 where postid='38';");    
    $result2 = mysql_num_rows($consulta2); 
    echo (string) $result2; 
?>
Dimitar
  • 4,402
  • 4
  • 31
  • 47
  • 5
    COUNT always returns a single row; read that one row, and the value in the row data is the count value.... note that it sometimes helps to use an alias with aggregation functions, making it easier to access the value from that row – Mark Baker Mar 30 '16 at 20:43
  • Because you select the number of rows `mysql_num_rows` instead of reading the result of the query. It will return 1 row with 1 field which holds the count – Jeroen van Langen Mar 30 '16 at 20:45
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 30 '16 at 21:11

3 Answers3

0

You can do either this:

  <? 
   $consulta2 = mysql_query("select count(*) as count from $tabla_db4 where postid='38';");    
   $result2 = mysql_fetch_array($consulta2); 
   echo $result2['count']; 
 ?>

OR

   $consulta2 = mysql_query("select* from $tabla_db4 where postid='38';");    
   $result2 = @mysql_num_rows($consulta2); 
   echo $result2; 
Ash
  • 27
  • 6
0

Solved! Please close.

$sql = mysql_query(
       "SELECT * FROM `comentarios` WHERE `postid` =
                                         $registro[id] ORDER BY `postid` DESC",$conexion_db);
$cuenta = mysql_num_rows($sql);
echo $cuenta;
Dimitar
  • 4,402
  • 4
  • 31
  • 47
-1

You can try this if you want to know how many rows there are:

<?php
    $query = "select count(*) as amount from $tabla_db4 where postid='38';";

    $result = mysql_query($query);

    if(!$result) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        die($message);
    }

    while($row = mysql_fetch_assoc($result)) {
        echo $row['amount'];
    }

    mysql_free_result($result);
?>

Also, are you sure postid is a string, since you're putting it in between quotes. It looks like it might be an integer. Mind the datatypes.

Bram
  • 2,718
  • 1
  • 22
  • 43