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?
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"];
The mysql_fetch_assoc
function fetches an associative array that represents one result row.
Try this:
$rowNum = mysql_query("SELECT COUNT(*) AS log_count FROM Logs");
$rows = mysql_fetch_assoc($rowNum);
$count = $rows["log_count"];
echo "Rows: " . $count;
See the documentiation for mysql_fetch_assoc on php.net for more info.
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
The MySQL development project has made its source code available under the terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL is also used in many high-profile, large-scale World Wide Web products, including Wikipedia, Google (though not for searches), Facebook, and Twitter. You can refer here to know more about MySQL Table which generates the web page document.