PHP Re-adds value to MYSQL on page refresh

im fairly new to php, but i know my way around, and ive done lots of research on this problem, but still cannot find the right solution to this. Here's my php code:

    <html>
    <head>
    <body>
    <form action="default.php" method="POST">
    <input type="text" name="hname">
    <input type="submit" name="submit" value="Submit">
    </form>
    <?php
    require("connect.php");
    $con = mysql_connect("mysql10.000webhost.com","$username","$password");
    $pname=$_POST[hname];
    mysql_query("INSERT INTO web_members(name) VALUES('$pname')");
    $result = mysql_query("SELECT * FROM web_members");
    while($row = mysql_fetch_array($result))
    {
    echo $row['name'];
    echo "<br />";
    }

    ?>

And basically it adds and displays the variable fine, but whenever i refresh the page it repeats the process. Can anyone help with this?

Upvotes: 0

Views: 160

Answers (2)

Ripa Saha
Ripa Saha

Reputation: 2540

use code like below

<?php
require("connect.php");
$con = mysql_connect("mysql10.000webhost.com","$username","$password");
if(isset($_POST[hname]))
{
   $pname=$_POST[hname];
   mysql_query("INSERT INTO web_members(name) VALUES('$pname')");
   header("location:default.php");
}
else
{
   $result = mysql_query("SELECT * FROM web_members");
   while($row = mysql_fetch_array($result))
   {
      echo $row['name'];
      echo "<br />";
   }
}

?>

hope it will help you. thanks.

Upvotes: 1

John Conde
John Conde

Reputation: 219804

You need to use the POST/REDIRECT/GET pattern for this. It prevents form resubmissions.

Upvotes: 0

Related Questions