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.