I am using the following code to try and insert data into my database. The data works fine and i do this using a form. The form has a submit button that i will but the code in bellow the following code. I am using localhost to run my web application.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO PRODUCTS (P_Name, P_Description, P_Price) VALUES ('$_POST[Name]', '$_POST[description]', '$_POST[Price]' ) ";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
the submit button:
<div id="theSubmit">
<input type="submit" name="submit">
</div>
At the moment when i click submit i get taken to a page display the text New record created successfully. However I would like it to reload the page.
I am aware of the javascript location.reload(); is this what I have to use, if so where?
You should reload after execution of your sql like this.
$_SESSION['msg'] = "New record created successfully";
header("Location: $url"); // tell the client to load $url
exit(); // stop further execution of the current script
the $msg
should be set via session to be able to show the msg after reload. If you do it like that it is no problem if the user klicks the back button or do a page reload.
After reload do:
if(isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
If you are not displaying any DOM Elements, or doing any Header requests prior that PHP Script you can always use the php function
header('Location: your-url.com');
exit();
to reload a website.
if there are header requests prior that header function this solution wont work so you can add that JS code at the bottom of your script so it gets fired after you have dealt with the form.
Use:
header("Location: $_SERVER[REQUEST_URI]");
exit;
This will redirect the user to the the same page using a GET
method, reloading it.