I created form that insert data in database but every time I reload the page the data insert again . I use unset($_POST) to fix it but it don't fix .
How I can make it insert only one time .
<form method="post" class="job">
<input type="text" placeholder=" course name" name="name" class="form-control input-lg">
<input type="text" placeholder=" country " name="country" class="form-control input-lg">
<input type="text" placeholder=" company " name="company" class="form-control input-lg">
<input type="date" placeholder=" start " name="start" class="form-control input-lg">
<input type="date" placeholder=" end " name="end" class="form-control input-lg">
<input type="text" placeholder="link" name="link" class="form-control input-lg">
<button type="submit" class="btn btn-warning btn-lg btn-block" name="addcourse" id="addcourse"> ADD COURSE </button>
</form>
</div>
<div class="col-lg-4"></div>
</div>
<?php
include("connect.php");
if (isset($_POST['addcourse'])){
$name = $_POST["name"];
$country = $_POST["country"];
$company = $_POST["company"];
$link = $_POST["link"];
$start=$_POST["start"];
$end=$_POST["end"];
$newcourse="INSERT INTO courses (name,country,company,start,end,link) VALUES ('$name','$country','$company','$start','$end','$link')";
if(!empty($name)&&!empty($country)&&!empty($company)&&!empty($link)&&!empty($start)&&!empty($end)){
if(mysql_query($newcourse)){
unset($_POST);
echo "<script> alert('insert successful'); </script>";
}
else{ unset($_POST);
echo "<script>alert('error'); </script>";
}}
else { unset($_POST);
echo "<script>alert('fill in all field'); </script>";}
}
?>
Since the request still contains all the values, when you refresh, Php will get the same values again. In the if statement where you check if the query is successful, add the line:
header('Location: <where you want the user to be sent to>');
If you want the user to end up the same place again, write:
header('Location: '.$_SERVER['PHP_SELF']);
First, I think you should understand that PHP is stateless, every time you call a script, it doesn't take into account previous actions like the unset of the POST array, which means the unset($_POST)
is useless.
Your problem is that everytime you reload the page, the $_POST['addcourse']
is always set. I would suggest changing this if (isset($_POST['addcourse'])){
with this if (!empty($_POST['name'])){
which would meant that the query would only be executed if the name field was set and the name wasn't empty.
You should also use the mysqli functions and prepared statements to prevent sql injection like in this example.