Jump to content

If there is a sql error redirect to a page


Vivid Lust

Recommended Posts

// Here is the function. This function must be placed before any HTML code or

// else the redirect will not work. You could place it in a separate file and

// use include.

function dbconnect($hostname, $username, $password, $database) {

$conn = @mysql_pconnect($hostname, $username, $password); // "@" is

necessary.

if(!$conn) header("Location: error.html");

if(!mysql_select_db($database, $conn)) header("Location: error.html");

}

 

 

The best way to handle specific errors is to use PHP5 and take advantage of Exception handling. This makes your life incredibly easier. Here is a very simplistic example of error handling to do what you are after:

<?php
/**
* Define your DBException class to trap DB errors
*/
class DBException extends Exception {}

try {
  if (mysql_connect(/* your connection info */) === FALSE)
  {
    throw new DBException('connection_error.php');
  }
} catch (DBException $e) {
  $file = $e->getMessage();
  header("Location: $file");
  exit;
} catch (Exception $e) {
  die('Unexpected error encountered: ' . $e->getMessage());
}
?>

 

Of course, a much better way to handle things would be to assign the error numbers to anything you wish and handle all the exceptions by error number rather than passing the filename through the message string, but this at least gives you the principle of exception handling.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.