By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

404 not found in PHP and MySQL

How to properly throw a 404 not found in PHP and MySQL.

Edited: 2013-03-21 06:53

To throw a 404 if something wasn't found in the database, all we really need to do, is to use the header function of PHP to throw the 404 not found error. We can then either echo some HTML/text to explain what went wrong, or we can include a custom error page.

$query = "SELECT * FROM ".$table." WHERE PostID = '".$PID."'";

$GetRow = mysql_query($query, $Connection);
$FoundData = mysql_num_rows($GetRow);
if ($FoundData < 1) {
  $ErrorMessage = 'The requested resource was not found on this Server.';
  header('HTTP/1.1 404 Not Found');
  include '404.php';
  mysql_close($Connection);
  exit();
}

The $ErrorMessage variable would then be echo'ed in the 404.php error page somewhere.

We use mysql_num_rows to check how many rows was returned, this should be safer then simply check if the query returned true or false, since it might otherwise return true under some circumstances.