简体   繁体   中英

Validation in my registration form is not working

I have created a simple registration form in php using PDO to store in backend. When I entered space bar it will take as empty fields in backend and if I didn't enter anything it doesn't show any error message.

<?php
session_start();
$errmsg_arr = array();
$errflag = false;
// configuration
$dbhost     = "localhost";
$dbname     = "pdo_ret";
$dbuser     = "root";
$dbpass     = "";

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];

if($fname == '') {
    $errmsg_arr[] = 'You must enter your First Name';
    $errflag = true;
}
if($lname == '') {
    $errmsg_arr[] = 'You must enter your Last Name';
    $errflag = true;
}
if($age == '') {
    $errmsg_arr[] = 'You must enter your Age';
    $errflag = true;
}
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: index.php");
    exit();
}
// query
$sql = "INSERT INTO members (fname,lname,age) VALUES (:sas,:asas,:asafs)";
$q = $conn->prepare($sql);
$q->execute(array(':sas'=>$fname,':asas'=>$lname,':asafs'=>$age));
header("location: index.php");
 ?>

If string with whitespace only is a wrong one, you should use trim function:

if(trim($fname) == '') {
    $errmsg_arr[] = 'You must enter your First Name';
    $errflag = true;
}
if(trim($lname) == '') {
    $errmsg_arr[] = 'You must enter your Last Name';
    $errflag = true;
}
if(trim($age) == '') {
    $errmsg_arr[] = 'You must enter your Age';
    $errflag = true;
}

You should use trim function but not in conditions but when assigning $_POST data

Instead of:

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];

you should have code:

$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$age = trim($_POST['age']);

Otherwise you will put data into database with possible white characters and it cause problems in future.

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