Page 1 of 1

mysql_num_rows

Posted: Tue May 10, 2005 6:55 am
by Stevey_G
Hi there. I was hoping you guys could shed some light on what could possibly be wrong with the mysql_num_rows function I am using. Here is the code:

Code: Select all

<html>
	<head>
    	<title>Coursework Details</title>
    </head>

    <body>
<?php

require 'connection.php';

if ($_GET['login_query'] === "") {

die("Invalid User: Authentication failed, please ensure that this is a valid HEMIS, please try again<br><br><a href=index.html>Back</a>");

}

else


$login_query = "SELECT * from students WHERE hemis_id = ".$_GET["login_query"]."";  //Selects HEMIS from db

$query_run = mysql_query($login_query) or die("Invalid Query: ".mysql_error());

$check = mysql_fetch_array($query_run);

$num_rows = mysql_num_rows($check);

echo ''.$num_rows.'';

if ($num_rows === 0) {

die("Invalid User: Authentication failed, please ensure that this is a valid HEMIS, please try again<br><br><a href=index.html>Back</a>");

}

else	{

while ($row = mysql_fetch_array($query_run)) {
	echo "Student Name: ".$row['forename']." ".$row['surname']."<br><br>";
        }

}

?>
</body>
</html>
Basically this function does not work, and either allows access to everyone OR disallows access to anyone, which is useful as you can imagine! I also get this error coming up in accordance to every line with the mysql_num_rows on it:

Warning: Supplied argument is not a valid MySQL result resource in /home/sites/site18/web/hemis_login.php on line 26

Any ideas? Im stumped

Jcart | Please review :arrow: Posting Code in the Forums

Posted: Tue May 10, 2005 6:59 am
by John Cartwright
Basically, you run a query and then you check the num rows.
Instead, you have ran the query, fetched the results, then checked the num rows.

Code: Select all

$query_run = mysql_query($login_query) or die(&quote;Invalid Query: &quote;.mysql_error());

$check = mysql_fetch_array($query_run);

$num_rows = mysql_num_rows($check);
should be

Code: Select all

$query_run = mysql_query($login_query) or die(&quote;Invalid Query: &quote;.mysql_error());

$num_rows = mysql_num_rows($query_run);

$check = mysql_fetch_array($query_run);
You should probably only fetch the results if the num rows is greater than 0.. else your just wasting time.

Posted: Tue May 10, 2005 8:05 am
by malcolmboston
better code

Code: Select all

$query = "SELECT * from students WHERE hemis_id = ".$_GET["login_query"]."";
$result = mysql_query($query) or die("Invalid Query: ".mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows >= 1)
{
  // theres a result, continue with array creation
  while ($array = mysql_fetch_array($result))
  {
    // do something with array here
  }
}
else
{
  // no results found
  print "No Results Found";
  exit;
}