views:

46

answers:

4

Hi there!

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

+5  A: 

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
kasperjj
would be more efficient, but his php warning is an clear indicator of a former error
Tobias P.
+1  A: 

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

Tobias P.
Thanks HEAPS GUYS! I've fixed it! :)
Hugo
then mark this question as solved ;)
Tobias P.
A: 

Can you try the follow code replacing the host, user, password and database with yours

<?php    

$link = mysql_connect("my_mysql_host", "mysql_user", "mysql_password");
mysql_select_db("my_database", $link);

$result = mysql_query("SELECT * FROM hacker", $link) or mysql_error();
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>
Prix
can you try to be a programmer? taking actions based not on the guessing and trying but on the certain error message?
Col. Shrapnel
Judging by the error he was getting i assumed it could be related to his connection include hence i posted a sample at any case you have the right not to like :)
Prix
It was my connect.php It was connecting to the wrong table.
Hugo
no problem, glad you got it working.
Prix
+2  A: 

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];
Col. Shrapnel