Redirect to user error page when duplicate record is created in MySQL

I am trying to redirect users to a user error page (for example: error.php) when a duplicate entry is created, this is a sample insert statement, but I don't know how to redirect it.

$values = $_POST;
foreach ($values as &$value) {
    $value = mysql_real_escape_string($value);
}

$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";

$result = mysql_query($sql1);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}
+3
source share
3 answers

The correct way to redirect form input is using HTTP 303 redirection .

To redirect in the current line, do it like this in PHP:

// Tell the browser to redirect
header('Location: /error.php', TRUE, 303);

// This ensures that the script doesn't continue
// Also, it shows the error on the off chance their browser doesn't redirect
die('Input error.');

You must ensure that the header function is enabled before any output.

Here it is in your code:

if (!$result) {
    header('Location: /error.php', TRUE, 303);
    die('Invalid query: ' . mysql_error());
} else {
    header('Location: /success.php', TRUE, 303);
    die('Success');
}
+2
source

You can redirect using header():

$url = "error.php";
header("Location: " . $url);

Make sure this is done before sending the HTML headers!

+1

, :

$query = "SELECT * FROM myDB WHERE loan_id = " . $values["loan_id"];
$result = mysql_query($query);
if (!$result) {
   echo "Wrong input";
} else {
   echo "right input";
}

echos ,

+1

All Articles