Form get's resent on refresh, I had read about header("Location:my_page.php")
unset($_POST)
, but I'm not sure where to place it.
This is our script, it works as need it, but it keeps re-sending on page refresh (Chrome browser alerts over and over), can some one fix the code and explain to my like 2 years old child.
<form action='thi_very_same_page.php' method='post'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_POST['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_POST['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
}
If you mean that the form data gets submitted again upon refresh, check this method
http://www.andypemberton.com/engineering/the-post-redirect-get-pattern/
You set your header to header('HTTP/1.1 303 See Other');
Data wont be cached, so when page refreshes the form data wont get submitted again!
The problem is you are using the
post
method to submit the form values so when ever you tries to refresh the browser asks you whether to send the form information or not it is the default behavior of the browser to tackle the posted information, the alternate solution for your problem is you can use theget
method like in form attributemethod='get'
what it does it will append all the information of form in the URL which we call thequery string
and in PHP code you are accessing the form values in$_POST
but when using get method the form values will now appear in the$_GET
method these methods are called request method and are PHP's global variables, Now when you try to refresh it will not ask you to resend information because the information now resides in the URLHope this is enough to explain you about the form submission one thing I will suggest you to deeply look at below