0

This is the html form (register.php):

<html>
<body>

<form action="handle_registration.php" method="post">

<fieldset><legend>Enter your
information in the form below:</legend>

First Name: <input type="text" name="fname" size="20" maxlength="40"><br>
Last Name: <input type="text" name="lname" size="20" maxlength="40"><br>
Username: <input type="text" name="uname" size="20" maxlength="40"><br>
Password: <input type="text" name="pword" size="20" maxlength="40"><br>
<input type="submit" name="submit" value="submit my info">

</form>

</body>
</html>

This is the php script that handles the registration (handle_registration.php):

<?php

// Create a shorthand for the form data:

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pword = $_POST['pword'];

// Create the connection variables:

$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "registration_info";
$con = mysqli_connect("$db_host", "$db_user", "$db_pass", "$db_name");

// Check the connection:

if (mysqli_connect_errno ())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Make sure all of the input boxes have a value:

if (empty($fname)) {
die('You forgot to enter your first name!');
}

if (empty($lname)) {
die('You forgot to enter your last name!');
}

if (empty($uname)) {
die('You forgot to choose a username!');
}

if (empty($pword)) {
die('You forgot to choose a password!');
}

// Insert the data from the form into the DB:

$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";

// Enter the info the end user type if everything is ok:

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}

// Close the connection:

mysqli_close($con);

?>

Here's the problem:

I want to submit the entered values into my database if all of the input fields have a value, but when I use the die function after checking to see if they're empty, then it kills the script. I just want to kill the part were it inserts it into my database if one or more of the fields are empty & display an error message that tells which field was empty. I'm not sure how to get around this and any help will be greatly appreciated.

3
  • refer this url: w3schools.in/php-tutorial/form-validation Commented Aug 7, 2013 at 5:15
  • 1. Store all errors in an array. if array is empty insert into database else print the array contents. Commented Aug 7, 2013 at 5:23
  • You will probably get a few comments, telling you to watch out for SQL-injection and security. That is one issue you should also be looking at. Another one is, whether it might be a better idea to check the form fields right where they originated from, i.e. by some JavaScript/jQuery validator in your client's browser. This way you can give the user a faster response in case of an error (or missing values) and you keep unnecessary traffic from your server. Commented Aug 7, 2013 at 5:24

4 Answers 4

2

The solution is rather simple. Just store the error message in a variable and before inserting rows into the DB - check weather the error is set or if it's empty. If it's empty - we can insert the row. Otherwise - let's show the error message.

// Currently we do not have an error
$error = NULL;

// Validate
if (empty($pword)) {
    $error = 'You forgot to choose a password!';
}

// If there are no errors - lets insert
if (!$error) {
    $sql = 'INSERT INTO ...';
}
Sign up to request clarification or add additional context in comments.

Comments

0

DOn't use die ,use some variable to store errors and print them later

 <?php

 // Create a shorthand for the form data:

 $fname = $_POST['fname']; $lname = $_POST['lname']; $uname =
$_POST['uname']; $pword = $_POST['pword'];

// Create the connection variables:

 $db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name =
 "registration_info"; $con = mysqli_connect("$db_host", "$db_user",
 "$db_pass", "$db_name");

 // Check the connection:

 if (mysqli_connect_errno ()) { echo "Failed to connect to MySQL: " .
 mysqli_connect_error(); }

 // Make sure all of the input boxes have a value:

 if (empty($fname)) { $error_msg[]='You forgot to enter your first name!'; }

 if (empty($lname)) { $error_msg[]='You forgot to enter your last name!'; }

 if (empty($uname)) { $error_msg[]='You forgot to choose a username!'; }

 if (empty($pword)) { $error_msg[]='You forgot to choose a password!'; }

 // Insert the data from the form into the DB:
 if(count($error_msg)==0){
 $sql = "INSERT INTO basic_information (First_Name, Last_Name,
 Username, Password) VALUES ('$_POST[fname]', '$_POST[lname]',
 '$_POST[uname]', '$_POST[pword]')";

 // Enter the info the end user type if everything is ok:

 if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
 else { echo "Record has been added"; }

 // Close the connection:

 mysqli_close($con);
}else{
print_r($error_msg);
}

 ?>

Comments

0

Full working example to stop insertion of empty data

<?php
          if (isset($_POST["submit"])) {
              $emptyInput = NULL;
              if (!($_POST["firstname"] == $emptyInput or $_POST["lastname"] == $emptyInput or $_POST["email"] == $emptyInput)) {
                  $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["email"] . "')";
                  if (mysqli_query($conn, $sql)) {
                      echo 'Record inserted successfully!';
                  }
              } else {
                  echo 'all fields are compulsory!';
              }
          }
          ?>  

Comments

-1

You could use a $errors variable to hold the errors with all the fields

$error = array();//initializing the $error
if (empty($fname)) {
$error[] = 'You forgot to enter your first name!';
}

if (empty($lname)) {
$error[] = 'You forgot to enter your last name!';
}

if (empty($uname)) {
$error[] = 'You forgot to choose a username!';
}

if (empty($pword)) {
$error[] = 'You forgot to choose a password!';
}

if(!empty($error))//if error occured
{
   die(implode('<br />', $error));//Stops the script and prints the errors if any occured
}
// Insert the data from the form into the DB:

$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";

// Enter the info the end user type if everything is ok:

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}

// Close the connection:

mysqli_close($con);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.