PDA

View Full Version : count rows returned in mysql



gusblake
01-16-2006, 06:26 PM
how do i count how many rows in a table contain a certain string? what i have so far is:
$result=mysql_query('SELECT username FROM users WHERE username=$username'); //($username = $_POST['username'])

then i use mysql_num_rows($result) to see how many it returns, but php says:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home2/haztuweb/haztuweb-www/gus/devvo/register_after.php on line 22

i know that i am connected, i have selected the database properly, users is a table and username is a column...

Twey
01-16-2006, 07:58 PM
Because the query isn't returning anything. As you're using single quotes, the string doesn't get parsed before use; what you're sending literally contains the string '$username', rather than substituting in the contents of $username as you probably intend. Also, in order to avoid SQL injection attacks, you should addslashes() any user-provided data you use in a query.

$result = mysql_query('SELECT username FROM users WHERE username=' . addslashes($username));

gusblake
01-16-2006, 08:16 PM
oh sorry, that was a mistake in my post. in the actual code, i was using double qoutes which if im right allow variables inside.. ill try adding addslashes to it
thanks, gus

Twey
01-16-2006, 08:38 PM
Also, you need to supply a database connection to which you want to send the query as the second argument.

gusblake
01-16-2006, 09:09 PM
the second argument is $link, the database connection and it still doesnt work... is it possible that it is showing me a warning because there are 0 rows returned?

Twey
01-16-2006, 09:31 PM
I don't think so, no; in any case, it certainly wouldn't give that warning. Are you sure the query is being executed OK?

gusblake
01-17-2006, 02:44 PM
ive sorted it out now, thanks for the help. i put 'or die(mysql_error())' on the $result line and mysql said something about the users table, so i dropped it and created it again and everything worked fine.