1

I have a form that takes input from the user and stores it in a MySQL database when the user submits the form.

print_r('<form action="" method="post">');
  /*
    form data, input tags, etc
  */
if (isset($_POST['Submit']))
{
    $sql = "INSERT INTO table
            VALUES (...)";
    $insert_form = $conn->query($sql);
}
print_r('</form>');

Initially, the user stayed on the page when they submitted the form and everything worked fine. However, I updated the site to take the user to a new page after the form is submitted. The first line of the above code now looks like this:

print_r('<form action="next-page.php" method="post">');

I didn't think it was a significant change, but now whenever I try to Submit the form, I am taken to the next page without an insert into the database. When I remove the form action, the insert command works, and when I put it back in, it does not.

Any idea why this problem is occurring?


I have found a workaround using the php header function:

if ($insert_form)
    header('Location: next-page.php');

..but it feels a little sloppy. Any comments on this?

2
  • 3
    Thats how it should be... either redirect after the insert or redirect and add the insert in the next-page.php Commented Nov 4, 2015 at 2:17
  • the action attribute makes you go to its value, +ignoring all the line below it. Commented Nov 4, 2015 at 2:23

2 Answers 2

1

You can remove the if statement; Insert next line after the $insert_form.

$sql = "INSERT INTO table
            VALUES (...)";
    $insert_form = $conn->query($sql);

    header("location: next-page.php");
Sign up to request clarification or add additional context in comments.

Comments

0

print_r is mostly used to print out an array.If you wanna write your html inside a php echo will do your job easily.Normally a form submits the data to the current page if there isn't set or no action.If there is action it will take the form value to that next php file which you have set on your action and doesn't process anything within your current page.

echo'<form action="" method="post">';

/*
  form data, input tags, etc
*/
echo'</form>';

if (isset($_POST['Submit']))
 {
  $sql = "INSERT INTO table
        VALUES (...)";
  $insert_form = $conn->query($sql);
          header("location: next.php");

 } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.