开发者

Connect to a MySQL database and count the number of rows

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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜