Sending data to the database only after sending was clicked on a form that displays the same page

advertisements

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.


"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:

  • How to fix "Headers already sent" error in PHP

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.