0

I have a registration page and I want to validate it. I have this code:

$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
  $First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
  $Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
  $email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
  $confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
  $mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
  $password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
  $confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
  $gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
  $day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
  $month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
  $year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
  $insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
  $agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
  $sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
  $result = $db->query($sql);
  if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
      if ($email == $row['email']) {
        $msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
        <br>Please sign in or enter a different email address. Please try again.</span>";
      }  if ($mobile_number == $row['mobile_number']) {
        $msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
        <br>Please sign in or enter a different number. Please try <br>again.</span>";
      }
    }
  } else {
// Insert into database and send email
}

Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.

Black P
  • 13
  • 6
  • 5
    **Warning:** You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](http://php.net/manual/en/pdo.prepared-statements.php) or by [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). – Dharman Feb 27 '19 at 22:57
  • Why not do an if for each check before you run the query? –  Feb 27 '19 at 23:00
  • Programming languages are very useful in automating mundane tasks. If at some point you find yourself in a situation where whenever you add a new field to the form you have to copy and paste a bunch of code, you should rethink your design. – Dharman Feb 27 '19 at 23:00
  • @Dharman so what should I do ?? I don't understand ?? – Black P Feb 27 '19 at 23:12
  • @Chipster can you give me an example on my code ?? – Black P Feb 27 '19 at 23:13
  • @BlackP See Dharman's answer. That's even better than what I was thinking/suggesting. –  Feb 28 '19 at 00:33
  • @BlackP as to SQL injection, see [How can I prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). That will tell how to make you invulnerable to that particular kind of attack –  Feb 28 '19 at 00:35
  • @BlackP Sorry, not Dharman's answer, I mean Markownikow's answer. –  Feb 28 '19 at 03:39

2 Answers2

2

If you will use same names in db as in form you could use something like this:

$keys = ['gender', 'email', 'mobile_number']; //etc

$errors = [];

while ($row = $result->fetch_assoc()) {
    array_walk($keys, function ($key) {
        if (empty($row[$key])) {
            $errors[] = "$key is required"
        }

        if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
            $errors[] = "please enter $key"
        }
    })
}

if you need to have more customized messages you might map keys to error text like:

$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];

while ($row = $result->fetch_assoc()) {
    array_walk($keys, function ($errorMsg, $key) {

        if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
            $errors[$key] = $errorMsg['equal'];
        }

        if (empty($row[$key])) {
            $errors[$key] = $errorMsq['empty'];
        }
    })
}
Markownikow
  • 457
  • 1
  • 4
  • 14
0
  1. Do not repeat
  2. Prevent SQL Injection

You can do something like this.

<?php
if(isset($_POST['submit'])) {

  $errors = [];

  function getPost($postIndex, $errorMessage = '') {
    global $errors;
    if (!empty( $_POST[$postIndex] )) {
      $value = $_POST[$postIndex];
      return $value;;
    } else {
      $errors[$postIndex] = $errorMessage;
      return null;
    }
  }

  function validateString($s) {
    return htmlspecialchars(trim($s));
  }

  getPost('First_Name', 'Firstname Cannot Be Empty');
  getPost('Last_Name', 'Lastname cannot be empty');
  $email = getPost('email', 'Your Error Message');
  getPost('confirm_email', 'Your Error Message');
  $mobile_number = getPost('mobile_number', 'Your Error Message');
  getPost('password', 'Your Error Message');
  getPost('confirm_password', 'Your Error Message');
  getPost('gender', 'Your Error Message');
  getPost('day', 'Your Error Message');
  getPost('month', 'Your Error Message');
  getPost('year', 'Your Error Message');
  getPost('insurance', 'Your Error Message');
  getPost('agree', 'Your Error Message');

  $stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');

  if (
    $stmt &&
    $stmt -> bind_param('ss', $email, $mobile_number) &&
    $stmt -> execute() &&
    $stmt -> store_result() &&
    $stmt -> bind_result($dbEmail, $dbMobileNumber) &&
    $stmt -> fetch()
  ) {

    if ($email == $dbEmail) {
      // email equal error message
    }  if ($mobile_number == $row['mobile_number']) {
      // mobile number equal error message
    }

  }

  if (count($errors)) {
    echo "You have an error";    
  }
  // or get the post index in your HTML form and show the error message there
  // <?php isset($errors['firstName']) ? echo $errors['firstname'] : null; 

}