I've created a html form
<form action="http://localhost/php/insert.php" method="post">
Barcode: <input type="text" name="barcode" /><br><br>
Serial: <input type="text" name="serial" /><br><br>
<input type="submit" />
</form>
which saves into my database using this php:
<?php
$con = mysql_connect("example","example","");
if ( ! $con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql = "INSERT INTO asset (barcode, serial)
VALUES ('$_POST[barcode]','$_POST[serial]')";
if ( ! mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
the form saves to the DB but the page just goes to http://localhost/php/insert.php
when you press submit, which is a blank page. how can I make it stay on the same page and just show a message or something?
Note that redirecting with HTTP_REFERER
is flaky and untrustworthy in general, so the best way is to have a URL sent with the request or, if it's coming from another server, you could build a specific pass-through to use for specific sites/URLs. The best is to know the URL by having it be submitted with the request; the other two are probably less than optimal.
After your form processing is done, do this before outputting anything (which will throw an error):
header("Location: {$_SERVER['HTTP_REFERER']}");
exit;
Depending on what your processing outcomes could be, you could append an error to the URL:
if ($query_does_not_execute) {
$errcode = "error_code=003";
}
$referer = $_SERVER['HTTP_REFERER'];
if ($errcode) {
if (strpos($referer, '?') === false) {
$referer .= "?";
}
header("Location: $referer&$errcode");
} else {
header("Location: $referer");
}
exit;
Then on the page, you could show the error. Or, alternatively, you could redirect to a page to handler errors of different kinds. This is wide-open to a number of different interpretations.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments