8

Why does my form send data twice after refreshing?

 3 years ago
source link: https://www.codesd.com/item/why-does-my-form-send-data-twice-after-refreshing.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Why does my form send data twice after refreshing?

advertisements

I have a form in my website, but I can't fix one problem. When I write some text in the form box, it sends the data to the database. When I hit refresh, the page sends the same data again, to the database. What is the problem with my code?

<?php
if(isset($_POST['submit']))
{
$err = array();

$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$uname = $_SESSION['uname'];
$date = "On " . date("F Y h:i:s A");

if (!isset($_SESSION['uname']))

$err[] = "You need to login";

else
{
if(empty($sub) && empty($msg))

$err[] = "All field required";

else
{
if(empty($sub))
$err[] = "Subject Requried";

if(empty($msg))
$err[] = "Message Requried";
 }
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red><b>$er</b></font>";
}
}
else
{
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
echo "Discussion was submitted";
}
}
}
?>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
name="discussion">
<table width="240" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="width:230;"><b>Select your Discussion</b>  
<select name="type">
<?php
$sqld = mysql_query("SELECT * FROM distype");

while($row = mysql_fetch_assoc($sqld))
{
$d_id = $row['d_id'];
$diss = $row['type'];
echo "<option value='$diss'>$diss</option>";
}
?>

</select></td>
</tr>
<tr>
<td><b>Subject</b></td>
</tr>
<tr>
<td><input type="text" name="sub" value="" size="33" class=""/></td>
</tr>
<tr>
<td><b>Message</b></td>
</tr>
<tr>
<td><textarea cols="30" rows="3" name="msg" class=""></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit Form"><br>
<td></td>
</tr>
</table>


On successful form submit you need to reload the url or redirect him somewhere to prevent user from inserting data to the database.

$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
   header("Location: page.php?mode=success");
   //or
   header("Location: ".$_SERVER['REQUEST_URI']); //which will just reload the page
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK