php check db and validate form

Viewed 26

I'm trying to validate and insert data into my database but it's not going as planned.

O boy, I'm dying! Here's my code

<?php if (isset($_POST['regBtn'])) {
$username = mysqli_real_escape_string($db_connection, $_POST['username']);
$emailId = mysqli_real_escape_string($db_connection, $_POST['emailId']);
$password = mysqli_real_escape_string($db_connection, $_POST['passwordID']);
$passwordConfirm = mysqli_real_escape_string($db_connection, $_POST['passwordConfirm']);


// form validations starts

if (empty($username) || empty($emailId) || empty($password) || empty($passwordConfirm)) {
    $_SESSION['message'] = "All Fields are required";
}

$usernameQuery = "SELECT username FROM users WHERE `username` = '$username'";
$runUsernameQuery = mysqli_query($db_connection, $usernameQuery);

if (mysqli_num_rows($runUsernameQuery) > 0) {
    $_SESSION['message'] = "Sorry, that username is taken";
}

$emailQuery = "SELECT email FROM users WHERE `email` = '$emailId'";
$runemailQuery = mysqli_query($db_connection, $emailQuery);

if (mysqli_num_rows($runemailQuery) > 0) {
    $_SESSION['message'] = "Somehow, that email is in our database";
}

if ($password == $passwordConfirm) {
    // query to insert
    } else {
        $_SESSION['message'] = "Something wen't wrong";
    }
} else {
    $_SESSION['message'] = "Password Dosn't match";
} } ?>

and I'm using sessions to catch the messages on the page where I want to display them. <?php if (isset($_SESSION['message'])) { echo $_SESSION['message']; } unset($_SESSION['message']); ?>

As you can see, the code only check if the password and the confirm password matches, if it does, then it insert the user. That's not good. I want to make sure it reads my db and check if a username and email already exists, if yes show error, if no, insert the user. Please point me to a good resource to learn, or better still explain it to me.

Thanks.

0 Answers
Related