SQL Number of rows

2019-08-29 15:27发布

问题:

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?

回答1:

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"];


回答2:

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.



回答3:

<?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";

?>


回答4:

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.



标签: mysql count rows