I have few input types on a form and a submit button as following:
<form id="register_form" method="post" role="form" action="">
<input autofocus="" id="firstname" name"firstname" placeholder="First Name" type="text" required />
<textarea id="Address" name="Adress" placeholder="No Address" type="text" rows="3" cols="30"></textarea>
<select id="country" name="country" required>
<option selected>Choose</option>
<option value="10">Germany</option>
<option value="11">Poland</option>
<option value="12">United Kingdom</option>
</select>
<button type="submit">Submit My New Entry</button>
</form>
Also i have a PHP code for submitting my data to a SQLite database:
<?php
try {
//open the database
$db = new PDO('sqlite:db/users.db');
$firstname = $_POST["firstname"];
$Address = $_POST["Address"];
$country = $_POST["country"];
//Insert record
$db->exec("INSERT INTO details
(firstname, Address, country)
VALUES ('$firstname', '$Address', '$country')");
$db = NULL;
} catch(PDOException $e) {
print 'Exception : ' .$e->getMessage();
}
?>
My problem is that every time i refresh the page the script cause to register a new entry into my databse with empty fields, even if some input fields are marked as required or the databse table is set to rollback on NULL value (both are ignored).
How can i avoid this?
PS. required works only if i press the submit button.
2
Answers
Your PHP script contains both the PHP and HTML (the form), so if you load this script, the PHP script will be triggered immediately, which will insert a blank record
(1) So, you should slightly amend the page so that only if there is form submission by POST (when someone submits the form), then to do the PHP part, by adding say :
(2) There is a typo in your HTML form, name="Adress" should be name="Address"
(3) Please use parameterized prepared statement in your PHP insert query to avoid SQL injection attacks
So the code is:
You just need to block the code from running.
This code, checks for the POST data and checks so there is content.
Then runs the database processing.
PHP
HTML: