1

Here is my sql:

<?php
$db=pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=preethy1970");
if (isset($_POST['signup'])) {
$query = "INSERT INTO users(user_name,user_password,user_email,user_phone,user_type) VALUES('$_POST[name1]','$_POST[password]','$_POST[email]','$_POST[phoneNumber]','$_POST[usertype]')";
$result=pg_query($query);
 }
?>

And here is the html:

<form method="post" action="signUp.php">
  <input id="submit-form" name="name1" placeholder="Name" type="text" required></input>
  <input id="submit-form" name="email" placeholder="Email id" type="email"></input>
  <input id="submit-form" name="phoneNumber" placeholder="Phone Number" type="tel"></input>
  <input id="submit-form" name="password" placeholder="Password" type="password"></input><br>
  <input name="usertype" type="radio" value="0">Student</input>
  <input name="usertype" type="radio" value="1">Faculty</input>
  <input name="usertype" type="radio" value="2">Alumni</input>
  <input id="submit-btn" type="submit" name="signup"  value="Sign Up"></input>
</form>

So I'll go to my signup page and add some contents, which will be added into the users table. When I reload the page, even though the fields are empty and the submit button is not clicked, the previous contents are added as a new row again. Why is this happening?

Niki
  • 173
  • 10

2 Answers2

0

This is happening because you're not distinguishing a form post and a page load. Every time the page is loaded, you are calling the php code. If you want it only to insert when the form is submitted, you need to check for $_POST["signup"] and run the SQL code only when if (isset($_POST['signup'])) returns true or has the "submit" value

richyen
  • 8,114
  • 4
  • 13
  • 28
  • So I have added an if condition, is it at the wrong place by any chance? Should be enclosing the entire thing (from $db) in the if condition? – Niki Nov 06 '20 at 03:07
  • have you tried it? I think you probably need to confirm whether it works as you intend for it – richyen Nov 06 '20 at 03:54
  • Yup, I tried it, didn't work as intended. For now, I think I'll just stick to redirecting – Niki Nov 07 '20 at 10:24
0

@richyen is correct.

"When a web form is submitted to a server through an HTTP POST request, attempts to refresh the server response can cause the contents of the original POST to be resubmitted, possibly causing undesired results, such as a duplicate web purchase."

This problem is well know and is solved by using the Post-Redirect-Get pattern.

Post-Redirect-Get

Here is another answer about it. https://stackoverflow.com/a/10827315/909973

And here is a simple Post-Redirect-Get implementation example. https://stackoverflow.com/a/4142969/909973

bassxzero
  • 4,838
  • 22
  • 34