I m trying a contact form in php where the details as to get stored in the database.If i dont enter any values it displays error msg but it gets stored in the database. How can I validate form when error message displays the data should not be entered in database.
Here is the code
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
} else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
} else {
$error .= "You didn't type your Mobile Number. <br />";
}
if (empty($error)) {
$success = "<b>Thank you! Your message has been sent!</b>";
}
}
?>
<div id="contactForm">
<?php
if (!empty($error)) {
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile)
VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
This is opposite of what it should be
if (!empty($error)) {
^
// your database stuff here
}
You should run that query when the error is empty, and not when its not empty.
if (empty($error)) {
// now save to database
}
Also go through How can I prevent SQL injection in PHP?
Check the condition on which you are inserting the data in the database. You are checking if (!empty($error)) which should denote that there is an error. Also since $error is a string, I would recommend you to check the values as if(trim($error) != "") rather than using empty()
you should use else if to check each condition..
if(isset($POST['submit'])){
if(empty($_POST['email'])){
$error[] = "email is required";
}
elseif(empty($_POST['name'])){
$error[]= "name is required;";
}
...
else{
$email = $_POST['email'];
$name = $_POST['name'];
// do all the stuff here
}
}
// also correct !empty ()
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`)
VALUES('".$name."','".$batch."','".$email."','".$mobile."');
You need to concatenate the strings. If you put $email in quotes, it will be considered a string and not a variable.
Related
i have an a project im using php and flutter for that
when i want to add a data to database i want to validate user inputs in php
im using a postman to test it i want to all inputs correct that add on database can some one help me?
when i request a post add and user want to add data to database i want all inputs correct as i defined on below if one inputs not correct i want to tell that filed incorrect and do not add a data utill all inputs correct
if ($_SERVER["REQUEST_METHOD"] === 'POST') {
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (empty($_POST['First_Name'])) {
echo 'Error! You didnt Enter the First Name. <br />';
} else {
$first_name = $_POST['First_Name'];
if (!preg_match("/^[a-zA-z]*$/", $first_name)) {
echo 'Only alphabets and whitespace are allowed For First Name. <br />';
}
}
if (empty($_POST['Last_Name'])) {
echo 'Error! You didnt Enter the Last Name. <br />';
} else {
$last_name = $_POST['Last_Name'];
if (!preg_match("/^[a-zA-z]*$/", $last_name)) {
echo 'Only alphabets and whitespace are allowed For Last Name. <br />';
}
}
if (empty($_POST['Email'])) {
echo 'Email Address Is Required <br />';
} else {
$email = $_POST['Email'];
if (!preg_match($pattern, $email)) {
echo 'Email is not valid! <br />';
}
}
if (empty($_POST['Phone'])) {
echo 'Phone Number is Required! <br />';
} else {
$phone = $_POST['Phone'];
if (!preg_match('/^[0-9]*$/', $phone)) {
echo 'Only Numeric Value Is Allowed. <br />';
} elseif (!preg_match('/^0\d{10}$/', $phone)) {
echo 'Invalid Phone Number!';
} elseif (preg_match('/^0\d{10}$/', $phone)) {
$re = "SELECT * FROM user WHERE Phone=$phone ";
$reresult = mysqli_query($conn, $re);
if (mysqli_num_rows($reresult) > 0) {
echo "user has already registered! <br />";
}
}
}
$first_name = mysqli_real_escape_string($conn, $_POST['First_Name']);
$last_name = mysqli_real_escape_string($conn, $_POST['Last_Name']);
$email = mysqli_real_escape_string($conn, $_POST['Email']);
$phone = mysqli_real_escape_string($conn, $_POST['Phone']);
$dob = mysqli_real_escape_string($conn, $_POST['DOB']);
$sql = "INSERT INTO `user` (`First_Name`,`Last_Name`,`Email`,`Phone`,`DOB` )
VALUES('$first_name','$last_name','$email','$phone','$dob')";
$query = mysqli_query($conn, $sql);
//$check=mysqli_fetch_array($query);
if ($query) {
echo ' user successfully added!';
} else {
echo 'failure';
}
//phone else
}
im asking to solve my problem
I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
$emailErr = ''; //it is a good practice to initialize variable before its use.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {
//insert it to the db.
//THIS IS INSECURE WAY - Check links in comments!
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
header('location: index.php');
exit();
I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.
I am validating an HTML Form with PHP. All of my code is fine, except the message field. If I put something in the message field and the other fields are displaying errors, it still submits. But, if I put something into the other fields and the other fields have errors, it won't submit, which is correct. I suspect it has something to do with the last if-else of my code. Thank you in advance.
contact.php
<?php
include 'includes/config.php';
$errors = FALSE;
$displayErrors = NULL;
if (isset($_POST['submit'])) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
//Clean Data to prevent malicous injections
mysql_real_escape_string(strip_tags(stripcslashes(trim($first))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($last))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($email))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($subject))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($message))));
if (empty($first)) {
$errors = TRUE;
$displayErrors .= 'First name is invalid.<br/>';
}
if (empty($last)) {
$errors = TRUE;
$displayErrors .= 'Last name is invalid.<br/>';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors = TRUE;
$displayErrors .= 'Email is invalid.<br/>';
}
if (empty($subject)) {
$errors = TRUE;
$displayErrors .= 'Subject is invalid.<br/>';
}
if (empty($message)) {
$errors = TRUE;
$displayErrors .= 'Message is invalid.<br/>';
} else {
$errors = FALSE;
//Database insertion goes here
echo 'Form submission successful. Thank you ' . $first . '.';
}
}
?>
Basically you are saying, if the message is not empty then $errors=FALSE, but you don't take into account all the other fields.
I'd suggest putting the errors in an array like:
$errors['email'] = true;
Then checking that array at the end using a foreach
Try turning that else into
if($errors == FALSE) {//just corrected the equality operator
//Database insertion goes here
echo 'Form submission successful. Thank you ' . $first . '.'
}
Before all of those ifs, you should put $errors = FALSE. Then instead of the else at the end of your code, you can put if(!$errors){ //database insertion here }
Make all your ifs else ifs
that way your last else will not mess up your validation.
First off, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I've tidied your logic, instead of using $error=true ect you should build an error array (containing your error text) and then check if thats empty at the end, I also cleaned up the magic quotes problem it seems your having, and the horrid multiple mysql_real_escape_string's, hope it helps
contact.php
<?php
include 'includes/config.php';
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
$errors = array();
if ($_SERVER['REQUEST_METHOD']=='POST') {
function clean(&$value){
if (get_magic_quotes_gpc()){
$value = mysql_real_escape_string(strip_tags(trim($value)));
}else{
$value = mysql_real_escape_string(trim($value));
}
}
array_walk($_POST,'clean');
if (empty($_POST['first'])) {
$errors['first']= 'First name is invalid.<br/>';
}else{
$first = $_POST['first'];
}
if (empty($_POST['last'])) {
$errors['last']= 'Last name is invalid<br/>';
}else{
$last = $_POST['last'];
}
if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Email is invalid.<br/>';
}else{
$email = $_POST['email'];
}
if (empty($_POST['subject'])) {
$errors['subject']= 'Subject is invalid.<br/>';
}else{
$subject = $_POST['subject'];
}
if (empty($_POST['message'])) {
$errors['message']= 'Message is invalid.<br/>';
}else{
$message = $_POST['messsage'];
}
if(empty($errors)){
//Database insertion goes here
echo 'Form submission successful. Thank you ' . htmlentities($first) . '.';
}else{
//Errors, so your have $errors['name'] ect to output
//so somthing like:
echo (isset($errors['name'])?$errors['name']:null);
}
}
?>
You should also perhaps add a condition that the value is a min certain length, with strlen($_POST['first']) > 2 ect.
I have created a simple form which has some required fields which if not completed will pass back an error to the user to inform them that the field is require.
As there are multiple field which is checks it can output multiple error messages.
I want to know how I can define an area on my form where these errors are displayed as at the moment these error simply display at the bottom of the form, which you can't see unless you scroll down the page.
Can I define where my error are displayed.
Here is the error checking code: EDIT
Old code was here
People in the past have suggested I make a loop to check for errors one at a time but I am novice at php so not sure how to do this.
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br/>";
}
//Code to check that the Tutor Name field is completed
if(empty($_POST['tutorName'] ))
{
$errors .="You did not select a tutor<br/>";
}
//Code to check that the Procedure field is completed
if(empty($_POST['procedure'] ))
{
$errors .="You did not enter a procedure<br/>";
}
//Code to check that the Grade field is completed
if(empty($_POST['grade'] ))
{
$errors .="You did not enter a grade<br/>";
}
//Code to check that the Student Reflection field is completed
if(empty($_POST['studentReflection'] ))
{
$errors .="You did not enter a reflection<br/>";
}
//Code to check if the tick box is checked that the tutor comment is entered
if( !strlen($_POST['tutorComments']) && isset($_POST['alert'] ))
{
$errors .="You must enter a reasan why you ticked the alert box";
}
//Code to check the password field is completed and correct
if (empty($_POST['password']))
{
$errors .="You did not enter you password";
}
if (!empty($_POST['password']))
{
//==========================================
// ESCAPE DANGEROUS SQL CHARACTERS
//==========================================
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$masterpass = $_POST['password'];
$masterpass = htmlspecialchars($masterpass);
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "username";
$pass_word = "password";
$database = "name of database";
$server = "server";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$masterpass = quote_smart($masterpass, $db_handle);
$SQL = "SELECT * FROM masterpass WHERE password = $masterpass";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
echo "";
}
else {
$errors .= "Password was not recognised";
exit();
}
}
mysql_close($db_handle);
}
}
if(!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
exit();
}
}
You could do something like
$errors = '';
if(empty($_POST['studentName']))
{
$errors .= "You did not enter the student name<br />";
}
if(empty($_POST['tutorName'] ))
{
$errors .= "You did not select a tutor name.<br />";
}
// etc.
and then above your <form> have
if (!empty($errors))
{
echo '<div class="errors">' . $errors . '</div>';
}
styling .errors with CSS so it'll stand out more. If $errors is blank higher up in your application logic, you can then perform the usual add / update to a database and redirect to a success page.
echo()ing your errors is what's adding them to the bottom. As the previous answer suggested, assigning them to a string and printing that in a defined div (if it's not empty) is how the pros do it!
Defining errors as an array also works, and allows you a bit more fine-grained control over the error process.
$errors = array();
if(empty($_POST['studentName']))
$errors[] = "You did not enter the student name";
if(empty($_POST['tutorName'] ))
$errors[] = "You did not select a tutor name.";
//etc...
//At the top of your page.
if (sizeof($errors)>0) {
echo "<div class='errordiv'>";
echo "<ul>";
foreach ($errors as $err) {
echo "<li>".$err."</li>"; //or whatever format you want!
}
echo "</ul></div>";
}
You can also pass the error array around as a parameter to other functions, log them, etc.