mysqlcountrows

SQL Number of rows


I am trying to pull the total number of rows in a SQL table.

I am using the following code:

$rowNum = mysql_query("SELECT COUNT(*) FROM Logs");
$count = mysql_fetch_assoc($rowNum);
echo "Rows: " . $count;

However, the output I get is Rows: Array rather than something like Rows: 10.

Any idea what I'm doing wrong?


Solution

  • mysql_fetch_assoc() returns an associative array with the result column names as keys and the result values as values. If you run var_dump($rowNum), you'll see an array with COUNT(*) as key and the number as value. You can use $rowNum["COUNT(*)"] or, better, alias the count expression and use the alias to refer to the value.

    $rowNum = mysql_query("SELECT COUNT(*) AS total FROM Logs");
    $count = mysql_fetch_assoc($rowNum);
    echo "Rows: " . $count["total"];