Snopzer
Snopzer

Reputation: 1692

php mysql error handling display in error in error page

$postQuery = $conn->query("SELECT * from table_name order by column desc")or die(mysql_error());

When there is error in query it ends the control and shows the error message in same page..

i want to redirect to an error page when error occurs and display the error in that page.

here is my Code :

$conn = new mysqli($host, $user, $password, $database);
    if ($conn->connect_error) {
        header("Location: ".SITEURL."/error.php?message=" . url_encode($conn->connect_error));
    } 

Any Suggestion.

Upvotes: 2

Views: 643

Answers (3)

Rohith K N
Rohith K N

Reputation: 871

This is a very general error handler, suitable for any type of errors

Add this in the page where error is being generated

 //error handler function
 function customError($errno, $errstr) {
       $errorpage= "Location:error.php?&err=".$eerrno." ". $errstr;
 }

 //set error handler
 set_error_handler("customError");

Now make the page to display your error,

error.php

<?php
$err=$_GET['err'];
echo $err;
?>

Upvotes: 2

Henrik
Henrik

Reputation: 189

try {
    $postQuery = $conn->query("SELECT * from table_name order by column desc")or die(mysql_error());
} catch (MySQLException $e) {
    header("Location: http://example.com/");
}

If you get another error than MySQLException, then just replace that exception.

Upvotes: 1

Caleb
Caleb

Reputation: 2298

When your mysql query fails, it returns a False, and the connection holds the error data, which you can reference as such:

if (!$conn->query("SELECT * from table_name order by column desc")) {
  header("Location: http://www.yoursite.com/error.php?errormessage=" . url_encode($conn->error));
}

Upvotes: 0

Related Questions