How to display error when no rows available?

Hey all

I have a MySQL Database with a coupe of rows and a page setup to display the data in mysql. To do so, I go to www.site.com/example.php?id=2 and it iwll bring me the row 2 of data from the database.

However, is it possible if someone enters www.site.com/example.php?id=100, it will bring out an error message if there is no id 100?

Thanks

It is possible. Check if the SQL result is empty, that is, check if no rows were returned. Usually, if the result is empty it gives false, so an if-else might do it.

use


	if(mysql_numrows($res) == '0'){
	echo 'no results';
	}
	else{
// do something
        }


That would work under the assumption you are using mysql function syntax (which is discouraged), but I’d rather see you not put the 0 in quotes and use ===

if (mysql_num_rows($res) === 0)
{
  // no results, return your error
}
else
{
  // put what you have currently here
}

If you are using mysqli, you can do one of the following

if (mysqli_stmt_num_rows($res) === 0)
{
  // no results, return your error
}
else
{
  // put what you have currently here
}

Or

// assumption you have a $mysqliObject
$stmt = $mysqli->prepare($query)
$stmt->execute();
if ($stmt->num_rows === 0)
{
  // no results, return your error
}
else
{
  // put what you have currently here
}

Then there is PDO

$stmt = $dbh->prepare('your query here');
$stmt->execute();
if ($stmt->rowCount() === 0)
{
  // no results, return your error
}
else
{
  // put what you have currently here
}

Thanks you all, and also cpradio because I’m using PDO and helped me on this issue (: