I tried what seemed like the most intuitive approach
$query = \"SELECT * FROM members
WHERE username = \'$_CLEAN[username]\'
AND password =
mysql_num_rows
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
If none match, then zero will be the return value and effectively FALSE
.
$result = mysql_query($query);
if(mysql_num_rows($result))
{ //-- non-empty rows found fitting your SQL query
while($row = mysql_fetch_array($result))
{//-- loop through the rows,
//-- each time resetting an array, $row, with the values
}
}
Which is all good and fine if you only pull out of the database. If you change or delete rows from the database and want to know how many were affected by it...
To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$result = mysql_query($query);
if(mysql_affected_rows())
{ //-- database has been changed
}
//-- if you want to know how many rows were affected:
echo 'Rows affected by last SQL query: ' .mysql_affected_rows();
mysql_query()
will only return FALSE
if the query failed. It will return TRUE
even if you have no rows, but successfully queried the database.
Use mysql_num_rows:
if (mysql_num_rows($result)) {
//do stuff
}
If you're checking for exactly one row:
if ($Row = mysql_fetch_object($result)) {
// do stuff
}
You can use mysql_fetch_array()
instead, or whatever, but the principle is the same. If you're doing expecting 1 or more rows:
while ($Row = mysql_fetch_object($result)) {
// do stuff
}
This will loop until it runs out of rows, at which point it'll continue on.
What about this way:
$query = "SELECT * FROM members WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
$result = mysql_fetch_array($result);
//you could then define your variables like:
$username = $result['username'];
$password = $result['password'];
if ($result)
{ ...
I like it because I get to be very specific with the results returned from the mysql_query.
-Ivan Novak
$result = mysql_query(...);
if(false !== $result)
{
//...
}
$sql = "SELECT columns FROM table";
$results = mysql_query($sql, $conn);
$nResults = mysql_num_rows($results);
if ($nResults > 0) {
//Hurray
} else {
//Nah
}
This should work.