连接到 MySQL 数据库并计算行数

发布于 2024-09-05 21:36:35 字数 476 浏览 6 评论 0原文

我需要连接到 MySQL 数据库,然后显示行数。这就是我到目前为止所得到的;

    <?php

include "connect.php";


db_connect(); 

$result = mysql_query("SELECT * FROM hacker"); 
$num_rows = mysql_num_rows($result); 


echo $num_rows; 

?>

当我使用该代码时,我最终出现此错误;

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Documents and Settings\username\Desktop\xammp\htdocs\news2\results.php on line 10

预先感谢:D

I need to connect to a MySQL database and then show the number of rows. This is what I've got so far;

    <?php

include "connect.php";


db_connect(); 

$result = mysql_query("SELECT * FROM hacker"); 
$num_rows = mysql_num_rows($result); 


echo $num_rows; 

?>

When I use that code I end up with this error;

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Documents and Settings\username\Desktop\xammp\htdocs\news2\results.php on line 10

Thanks in advance :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

傲鸠 2024-09-12 21:36:36

养成以这种方式运行所有查询的习惯:

$sql   = "SELECT * FROM hacker";
$res   = mysql_query($query) or trigger_error(mysql_error().$sql);

您将始终获得全面的错误信息
并采取适当的更正

,正如上面提到的,计算行数的唯一可靠方法是 SELECT count(*) 查询

$sql   = "SELECT count(*) FROM hacker";
$res   = mysql_query($query) or trigger_error(mysql_error().$sql);
$row   = mysql_fetch_row($res);
$count = $row[0];

take a habit to run all queries this way:

$sql   = "SELECT * FROM hacker";
$res   = mysql_query($query) or trigger_error(mysql_error().$sql);

and you will always have comprehensive error information
and take appropriate corrections

also, as it was mentioned above, the only reliable way to count rows is SELECT count(*) query

$sql   = "SELECT count(*) FROM hacker";
$res   = mysql_query($query) or trigger_error(mysql_error().$sql);
$row   = mysql_fetch_row($res);
$count = $row[0];
浮生未歇 2024-09-12 21:36:36

更改您的代码如下:

$result = mysql_query("SELECT * FROM hacker");
echo mysql_error();

您有 SQL 错误或未连接到数据库

change your code as following:

$result = mysql_query("SELECT * FROM hacker");
echo mysql_error();

You have an SQL-Error or your not connected to the database

感情洁癖 2024-09-12 21:36:35

您可能最好要求数据库聚合行数,而不是将它们全部传输到 php 并在那里进行计数。

SELECT COUNT(*) FROM hacker

You would probably be better of asking the database to aggregate the number of rows instead of transferring them all to php and doing the counting there.

SELECT COUNT(*) FROM hacker
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文