简体   繁体   中英

Validation for registration page in PHP

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.

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'];
        }
    })
}
  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; 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM