0

I'm performing a query to check if a user exists before adding it to the database. If that result comes back then die and echo 'username already exists' but if it comes back empty then add the new user to the database.

For some reason it just adds a new user to the database anyway.

        //If post was 
        if (isset($_POST['submit'])) {

        // Check if username is blank
        if (!isset($_POST['username']) || empty($_POST['username'])) {
            echo "Username was blank<br />";
            die();
        } else {
            $username = mysqli_real_escape_string($connection, $_POST['username']);
        }

        // Check if password is blank
        if (!isset($_POST['password']) || empty($_POST['password'])) {
            echo "Password was blank<br />";
            die();
        } else {
            $password = mysqli_real_escape_string($connection, $_POST['password']);
            $password2 = md5($password);
            //echo $password;
        }

        // Check if email is blank
        if (!isset($_POST['email']) || empty($_POST['email'])) {
            echo "Email was blank<br />";
            die();
        } else {
            $email = mysqli_real_escape_string($connection, $_POST['email']);
            //$password = md5($password);
            //echo $password;
        }

        //Check to see if username alread exsists 
        $query_check = "SELECT * FROM users WHERE user = '$username' LIMIT 1";
        $result_check = mysqli_query($connection, $query_check);

         if(count(mysqli_fetch_array($result_check)) === 1) {
            echo "Username exists.";
            die();   

         } else {
                $query = "INSERT INTO users (user, pass, email) VALUES ('$username','$password2','$email');";
                $result = mysqli_query($connection, $query);
                if($result){  // returned TRUE, e.g. in case of a DELETE sql  
                    $_SESSION["username"] = $username;
                    header("Location: ../profile.php");

                } else { // returned FALSE
                    //echo "Error: " . mysqli_error($connection);
                    echo "Error during register <a href='../register.php'>Back To Register</a>";
                    die();
                }
         }



    } else {
        header("Location: ../index.php");
}

2 Answers2

3

After taking a few minutes testing your code, found that you're using the wrong function.

mysqli_fetch_array():

Fetch a result row as an associative, a numeric array, or both

You're trying to fetch an associative array.

As opposed to mysqli_num_rows():

Gets the number of rows in a result

Replace (and which seems to have been taken from Félix's answer)

if(count(mysqli_fetch_array($result_check)) === 1)

with

if(mysqli_num_rows($result_check) == 1)

or

if(mysqli_num_rows($result_check) > 0)

Your original post contained:

if(mysqli_fetch_array($result_check) === 1)

which still stands to be the wrong method.


if(mysqli_num_rows($result_check) >0) and make sure $username is defined. We don't know how/where if it is even defined.


Now, if THAT fails, then your form element isn't named, and/or something else in your form is failing you.

I.e.: <input type="text" name="username">


Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.


Regarding using MD5.

That isn't considered safe to use anymore, as far as password hashing goes.

  • That technology is old and is considered broken.

For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.

For PHP < 5.5 use the password_hash() compatibility pack.


Pulled from ircmaxell's answer which uses PDO with prepared statements and password_hash():

Just use a library. Seriously. They exist for a reason.

Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.

$dbh = new PDO(...);

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);

$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);

And on login:

$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
    if (password_verify($_POST['password'], $users[0]->password) {
        // valid login
    } else {
        // invalid password
    }
} else {
    // invalid username
}

Footnotes:

I noticed you are using headers.

You should add exit; after each header. Otherwise, your code may want to continue executing.

header("Location: ../profile.php");
    exit;

and do the same for the other one also.

You're also using sessions. session_start(); isn't present in your posted and will fail if it isn't included; an insight.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
1

here

 if(mysqli_fetch_array($result_check) === 1) {

the value returned by mysqli_fetch_array won't be an integer but an array. You seem to want to count it:

 if(count(mysqli_fetch_array($result_check)) === 1) {

In the case somehow two users would have been inserted for whatever reason, checking if count is greater than 0 may prevent a third one being inserted:

 if(count(mysqli_fetch_array($result_check)) > 0) {