0

I am trying to INSERT data into a database from a PHP form. I have written the code below but I do not understand why everytime I refresh the form it adds a new row with the previously entered data into my Database. If someone could help me fix this issue, please.

<! DOCTYPE html>

<html>
<head>

<style>
.error {color: #FF0000;}
</style>
</head>

<body>  

<?php include 'config.php'; ?>


<?php


     if(isset($_POST['submit'])) {
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $addr = $_POST['addr'];
        $phone = $_POST['phone'];



    $query = "INSERT INTO `employee`(fname,lname,addr,phone) VALUES ('$fname','$lname','$addr','$phone')";
    $result = mysqli_query($con,$query) or die ("problem inserting new product into database");



     }


    ?>
    <h2>Sign Up</h2>
    <h3>Enter the data to Sign Up</h3>
    <p><span class="error">* required field</span></p>

    <form action = "" method = "post">
    Name: <input type = "text" name = "fname">
    <span class=error>*</span><br>
    Surname: <input type="text" name="lname">
    <span class=error>*</span><br>
    Address: <input type = "text" name = "addr">
    <span class=error>*</span><br>
    Phone Number: <input type = "tel" name="phone"><br>

    <input type = "submit" name="submit" value="Submit">
    </form>

</body>
</html>
4
  • Real simple; you need to use a conditional empty() around all of your user inputs. Then add a header. Commented Apr 27, 2018 at 12:43
  • Btw, if you value your work and the data, use a prepared statement. You're bound to get hacked. Commented Apr 27, 2018 at 12:46
  • I take it you don't care about security then. Oh well, I just hope you don't come back to us and say that your database suddenly disappeared. Commented Apr 27, 2018 at 12:58
  • I just started learning so I was trying to do something simple at first until I got the hang of it Commented Apr 27, 2018 at 19:35

1 Answer 1

1

When you validate a form, you create POST values in th eheader of your page. If you reload your page which has just undergone an action, it will repeat itself.

Just after

$result = mysqli_query($con,$query) or die ("problem inserting new product into database");

You can add

header('Location : nameofyourpage.php')

or

unset($_POST)
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, the "header..." option worked.
Even though this is somewhat of a solution, it won't help it much if any of the inputs are left empty.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.