SQL Number of rows

本秂侑毒 提交于 2019-12-12 03:05:03

问题


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.



来源:https://stackoverflow.com/questions/8143505/sql-number-of-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!