0

I'm trying to get some form validations to work, but my script registers a user even if the data is incorrect and doesn't validate.

Also, what should I write so it can check whether the user is already in the database and return an error if so?

For example, if I just typed "aaaa" in all text boxes, it would register the user. What should happen if a user entered incorrect data (wrong format) is an error message should appear, and it should not register until the user enters correct data. But it registers the user no matter what I enter, as if there were no validations written.

<?php

include "db.php";

// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $passwordErr = $cpasswordErr = "";
$cpassword = "";
$cust_email = $cust_username = $cust_password = $cust_fullname = $cust_country = $cust_dob = $cust_gender = $cust_phone = "";

if (isset($_POST["btnsignup"])) {
    //Username Validation
    if (empty($_POST["txtcust_username"])) {
        $nameErr = "Name is required";
    } else {
        $cust_username = test_input($_POST["txtcust_username"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z0-9]*$/", $cust_username)) {
            $nameErr = "Only letters, numbers are allowed and no white space allowed";
        }
    }
    //Email Validation
    if (empty($_POST["txtcust_email"])) {
        $emailErr = "Email is required";
    } else {
        $cust_email = test_input($_POST["txtcust_email"]);
        // check if e-mail address is well-formed
        if (!filter_var($cust_email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
    //Password Validation
    if (!empty($_POST["txtcust_password"]) && ($_POST["txtcust_password"] == $_POST["txtcust_cpassword"])) {
        $cust_password = test_input($_POST["txtcust_password"]);
        $cust_cpassword = test_input($_POST["txtcust_cpassword"]);
        if (strlen($_POST["txtcust_password"]) <= '6') {
            $passwordErr = "Your Password Must Contain At Least 6 Characters!";
        } elseif (!preg_match("#[0-9]+#", $cust_password)) {
            $passwordErr = "Your Password Must Contain At Least 1 Number!";
        } elseif (!preg_match("#[A-Z]+#", $cust_password)) {
            $passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
        } elseif (!preg_match("#[a-z]+#", $cust_password)) {
            $passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
        }
    } elseif (!empty($_POST["txtcust_password"])) {
        $cpasswordErr = "Please Check You've Entered Or Confirmed Your Password!";
    }

    $cust_fullname = $_POST['txtcust_fullname'];
    $cust_country = $_POST['txtcust_country'];
    $cust_dob = $_POST['txtcust_dob'];
    $cust_gender = $_POST['txtcust_gender'];
    $cust_phone = $_POST['txtcust_phone'];

//Insert Into Table
    $insert = "INSERT INTO customer (cust_email,cust_username,cust_password,cust_fullname,cust_country,cust_dob,cust_gender,cust_phone)
VALUES ('$cust_email','$cust_username','$cust_password','$cust_fullname','$cust_country','$cust_dob','$cust_gender','$cust_phone') ";

    $run = mysqli_query($conn, $insert);
    if ($run) {
        setcookie("Name", $cust_username);
        header("Location: home.php");
    } else
        echo "User has not been Add";
}
function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • "[I]f the data is incorrect" in what way? Questions seeking debugging help ("**why isn't this code working?**") must include the desired behavior, a *specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example.](http://stackoverflow.com/help/mcve) – elixenide Dec 14 '16 at 16:08
  • @ed Thanks for your reply, I mean for example if I just typed "aaaa" in all text box it would register the user, So it register the user no matter what I enter. – Mohammed Mounir Dec 14 '16 at 16:11
  • Okay, so what? We can help you detect specific patterns or answer specific problems with validation, but if you're asking us to help you write a general "bad information" detector, that's way too broad for this site. – elixenide Dec 14 '16 at 16:20
  • @EdCottrell Thanks, I'm still new in php, I tried to ask in FB and didn't get answer, So I asked here. Can you tell me where should a beginner like me ask a question when I can't solve it by myself. Thank again. – Mohammed Mounir Dec 14 '16 at 16:25
  • Your code snippet includes way too much unnecessary information. Please reduce it to contain only your problem. Please define "incorrect data". – Guillaume CR Dec 14 '16 at 16:26
  • @GuillaumeCR Thanks for your reply, But it's just the validations with the insert statement, I'm not sure what exactly I should add so someone and see where the issue come from, By incorrect data I mean if I entered wrong format in the text box. – Mohammed Mounir Dec 14 '16 at 16:35

1 Answers1

0

TL;DR You do a bunch of validation and set a bunch of error messages, but then ignore all of that and run the INSERT no matter what. Add an if/else statement to handle validation errors or do the insert.

Let's break this down. Your code isn't really a Minimal, Complete, and Verifiable Example, but we can make it into one. Stripping out all the unnecessary stuff, your code is basically this:

<?php

include "db.php";

// initializing some variables
// ...

// a bunch of validation stuff, where you set
// variables like $nameErr and $emailErr
// ...

// logic where you initialize $cust_fullname, $cust_country, etc.
// ...

/***************************************************************
 * The database insertion, without ever checking whether
 * the data validated!
 ***************************************************************/
//Insert Into Table    
$insert = "INSERT INTO customer (cust_email,cust_username,cust_password,cust_fullname,cust_country,cust_dob,cust_gender,cust_phone)
VALUES ('$cust_email','$cust_username','$cust_password','$cust_fullname','$cust_country','$cust_dob','$cust_gender','$cust_phone') ";

$run = mysqli_query($conn,$insert);
// more code not relevant here...

?>

So, you just run the INSERT, regardless of what happens in the validation stage. There's your problem.

As for your second question (how to check for an existing user), that's a little broad for this site, and you generally should only ask one question at a time. Please try something first, then post that as a second question if you get stuck.

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • Thanks, but after adding `else` before the `Insert` and ending it before `$run`' I'm getting error `Parse error: syntax error, unexpected 'else' (T_ELSE)` – Mohammed Mounir Dec 14 '16 at 16:42
  • You can't just add an `else`; it has to follow an `if`. In other words, you need something like `if (/* any of those error message is set */) { /* tell the user */ } else { /*do the insert*/ }`. Also, by the way: you really should break this code up into methods or functions. A giant blob of `if`/`else`s to validate your input should not be part of the same code that does database interactions, output, etc. – elixenide Dec 14 '16 at 16:54
  • Oh, and it doesn't make sense to put only the line `$insert = "...";` in the `else` block. The line containing `mysqli_query(...)` is the one that matters. – elixenide Dec 14 '16 at 16:55
  • I did this but not sure if it's correct `if($nameErr || $emailErr || $passwordErr || $cpasswordErr){ echo "User has not been Add"; } else{ $run = mysqli_query(...)` – Mohammed Mounir Dec 14 '16 at 17:29
  • But when I click submit I'm getting `Undefined index: txtcust_fullname, txtcust_country....` – Mohammed Mounir Dec 14 '16 at 17:30
  • @EgyMMM That means you don't have any POSTed data by those names. See [this post](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) for more information. In the meantime, please consider accepting this answer (clicking on the check mark), since it helped you identify your problem (your validations weren't being used). You can ask another question if you need help with other errors or problems. – elixenide Dec 14 '16 at 17:34
  • Okay, Thank you very much. – Mohammed Mounir Dec 14 '16 at 17:57