0

I have a form that posts to the same page because I need the values to display below after submit has been clicked, which it does. The problem is that as soon as the page is loaded, the php runs and sends the data to the database instantly, so it sends an empty value to the database since the user has not submitted anything.

$servername = "localhost";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO my_table (firstname) 
    VALUES (:firstname)");
    $stmt->bindParam(':firstname', $firstname);

    // insert a row
    $firstname = $name;
    $stmt->execute();

    echo "New records created successfully";
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>

<form method="post" id="nick-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
    Name: <input type="text" name="name" value="<?php echo $name;?>">
    <input type="submit" name="submit" value="Submit"> 
</form>
<?php
    echo "<h2>Your Input:</h2>";
    echo $name;
?>

I would like the $name variable to only get sent when the user hits submit, if possible.

Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95

3 Answers3

4

"I would like the $name variable to only get sent when the user hits submit, if possible."

Use a conditional isset() with your submit button.

<?php

if(isset($_POST['submit']))
{

    // code to execute

}

Sidenote: You could/should also add an !empty() on your inputs also, which is highly recommended in order to prevent empty submissions.

You could also implement a header upon successful submission to redirect to another page:

header('Location: http://www.example.com/');
exit; // avoid further execution of code, if any resides below that

Just make sure you're not outputting before header if you plan on using it.

Here's an article on Stack about this:


There is also a good article on how to prevent multiple submits using sessions and tokens:

Something I have used in the past with success which could be useful.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 1
    I like your preventing multiple form submission link. Cheers. – Martin Apr 20 '15 at 20:53
  • @Martin Yes, it's very good. I remember looking for something myself a few years ago to prevent that and came upon that great article. I still use it to this day, *cheers* :-) – Funk Forty Niner Apr 20 '15 at 20:55
2

What you have is a possible checking clause with an if statement using

    if (count($_POST) > 0) {
    //code runs if POST is submitted data
        if (!empty($_POST['name'])){
          ///process the name form field value
         }
    }

Which would solve your issue, BUT when the page is refreshed by the user, the refreshed page will also resubmit the POSTED data , this is why on database activity pages it is HIGHLY advisable to send the data to another page, and then once the data is saved, return the browser to the original page, so refreshing the original page does not resubmit the POSTED data

To illustrate further, make another PHP file called "save.php" and everything in the PHP tags ABOVE the <form> element, put in the save.php file, then set the form to goto save.php and at the bottom of the save.php set a header("location:formpage.php");die(); to return to the form.

You will still need a database call on the form page to display the desired output. But this will prevent resubmitting of data upon page refresh

Martin
  • 22,212
  • 11
  • 70
  • 132
  • 1
    Thank you for that information. I was trying really hard to keep it all on one page but I see the benefits of sending it to another are greater. – Mr.Smithyyy Apr 20 '15 at 20:40
1

You can use if :

if(isset($_POST['name']) && $_POST['name'] != null) {
  // Your code
}

You should also check $_POST['submit'].

Lavik
  • 31
  • 3