Reputation: 119
im trying to use this query:
mysql_query("SELECT COUNT(*) FROM Users WHERE (Username=" + $username + "AND Hash=" + $hash + ")")
to return the number of rows for authentication in a php script. but this doesnt return an int? how do I use the return value to get the number of rows?
Upvotes: 0
Views: 119
Reputation: 838226
You can use mysql_fetch_array
to fetch rows from the result:
$result = mysql_query("SELECT COUNT(*) FROM Users WHERE ...") or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row[0];
Or since you only need to fetch a single value you can do this more briefly using mysql_result
:
$result = mysql_query("SELECT COUNT(*) FROM Users WHERE ...") or die(mysql_error());
echo mysql_result($result, 0);
I'd also suggest that you look at parameterized queries instead of building your SQL queries using string concatenations.
Upvotes: 2
Reputation: 449435
Your immediate problem is that you are using +
instead of .
to concatenate strings.
And the values for username
and hash
will need quotes around them so they don't break the query:
mysql_query("SELECT COUNT(*) FROM Users WHERE (Username='" . $username . "' AND Hash='" + $hash . "')")
Be sure to add proper error checking to your mysql_query()
calls as shown in the manual.
Also be sure you are aware of SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string()
for the classic mysql library) for all values, or switch to PDO and prepared statements.
Upvotes: 2
Reputation: 3209
one way of doing it is:
$result = mysql_query("SELECT username FROM Users WHERE (Username='" . $username . "' AND Hash='" . $hash . "') LIMIT 1");
$returned = mysql_numrows($result);
echo $returned ." users";
However you can optimize the query further more depending on what you are doing with the result set.
Take a look at http://php.net/manual/en/function.mysql-num-rows.php As well as the http://www.php.net/manual/en/function.mysql-fetch-array.php and other mysql_fetch_* functions
Also, make sure you format your query properly. Look at mysql_real_escape_strings to escape user input to avoid SQL injection attacks.
Upvotes: 0
Reputation: 163240
$row = mysql_fetch_row($your_resource);
echo (int)($row[0]);
Also, you are likely wide open to SQL injection. You should really learn to do prepared queries with PDO.
Upvotes: 0