I have created a form (enquiry form) in HTML that posts to the following code:
<?php
if(isset($_POST['submit']))
{
$name = mysql_real_escape_string((string)$_POST['name']);
$surname = mysql_real_escape_string((string)$_POST['surname']);
$email = mysql_real_escape_string((string)$_POST['email']);
$phone = mysql_real_escape_string((string)$_POST['phone']);
$country = mysql_real_escape_string((string)$_POST['country']);
$message = mysql_real_escape_string((string)$_POST['message']);
$sql = "INSERT INTO contact
(name, surname, email, phone, country, message)
VALUES('$name', '$surname', '$email', '$phone', '$country', '$message')";
mysql_select_db($db);
$retval = mysql_query( $sql, $conn )or die(mysql_error());
echo 'Thank you '.$name.' '.$surname.'. Your enquiry has been forwarded to our team. <br><br>Please check you email inbox for further information.<br><br>Return to homepage:<br><br><button class="search" onclick="/">Return to homepage</button>';
mysql_close($conn);
}
?>
I am wondering, how I can display errors and stop the form posting when invalid or zero data is entered?
Whilst learning how to create forms on the web, I also heard about SQL injections. Am I protected?
Help much appreciated.
You have to do the validation after
if(isset($_POST['submit'])). For example you could check is name is non empty:For more complicated validations such as validating that email is valid, you should take a look at the filter extension:
And after all your validations:
You could use a while block to break as soon as you detect an error:
Yes, as long as you escape anything that you embed in a SQL query (just like you are doing), you are protected.
You should try using prepared statements, this is safer and easier to use.