I'm trying to perform a form register validation but I don't know if I'm doing it right.
First I'm storing an error message for each blank field in my form. After that if my fields aren't empty I want to validate the username field (from having invalid characters), password and email
The problem is when I delete the die(); line in my username validation conditional, it does show me both the error message and the succes message and the invalid username is inserted in my database.
I'm pretty sure the problem is in my if($numrows==0) conditional but I can't figure it out why.
<?php
session_start();
$con=mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
if(isset($_POST["submit"])){
$arrErrors = array();
unset($_SESSION['errors']);
if($_POST['user'] == ''){
$arrErrors['user_not_completed'] = "Username is not completed!";
$_SESSION['errors'] = $arrErrors;
header("Location: register.php");
}
if($_POST['pass'] == ''){
$arrErrors['pass_not_completed'] = "Password is not completed!";
$_SESSION['errors'] = $arrErrors;
header("Location: register.php");
}
if($_POST['email'] == ''){
$arrErrors['email_not_completed'] = "Email is not completed!";
$_SESSION['errors'] = $arrErrors;
header("Location: register.php");
}
if(!empty($_POST['user']) && !empty($_POST['pass']) && !empty($_POST['email'])) {
$user=$_POST['user'];
$pass=$_POST['pass'];
$email=$_POST['email'];
if(!preg_match("/^[a-zA-Z'-]+$/",$user)) {
$arrErrors['invalid_user'] = "Username is invalid!";
$_SESSION['errors'] = $arrErrors;
header("Location: register.php");
die();
}
$query=mysql_query("SELECT * FROM users WHERE username='".$user."'");
$numrows=mysql_num_rows($query);
if($numrows==0){
$sql="INSERT INTO users(username,password, email) VALUES('$user','$pass', '$email')";
$result=mysql_query($sql);
if($result){
$arrErrors['succes'] = 'Account successfuly created!';
$_SESSION['errors'] = $arrErrors;
header("Location: register.php");
}
} else {
$arrErrors['already_exists'] = 'That username already exists!';
$_SESSION['errors'] = $arrErrors;
header("Location: register.php");
}
}
}
?>