0

I have created a if statement that is to check if a username is stored on the SQL database, I am not sure why when it checks the database it always finds that there is a username already inserted even when the database can be empty.

I have tried various variations of an if statement and I am not having much luck.

<?php
    if(isset($_POST['save'])){
        include 'includes/config.php';

        $fname = $_POST['fname'];
        $pass = $_POST['pass'];
        $gender = $_POST['gender'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $location = $_POST['location'];

        $check = "SELECT email FROM client WHERE email = '$email'";
        $res_e = mysqli_query($db, $check);

        if (mysqli_num_rows($res_e) == 0) {
            echo "<script type = \"text/javascript\">
    alert(\"Sorry... username already taken.\");
    window.location = (\"signup.php\")
    </script>";
        } else {
            $qry = "INSERT INTO `client` 
    VALUES('NULL','$fname','$email','$pass','$phone','$location','$gender', 
    'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL')";

            $result = $conn->query($qry);

            echo "<script type = \"text/javascript\">
    alert(\"Successfully Registered.  Proceed to Login.\");
    window.location = (\"account.php\")
    </script>";
        }
    }

I just need it to check if the username (email address) is stored and return that the username is already taken or if not already taken to insert the data into the database.

treyBake
  • 6,440
  • 6
  • 26
  • 57
Valikahn
  • 23
  • 2
  • 3
    I think your check is the wrong way around. You're saying that if the number of found rows is equal to 0 that the username is already taken. But if there are no rows found it of course means that the username is NOT taken. Also take a look at this post to prevent SQL injection: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Dirk Scholten May 16 '19 at 09:01
  • 1
    Even if you got this to work, this approach is prone to race conditions. You should add a `UNIQUE` constraint on the `email` column, try to insert a row, and if it fails with a constraint error, you know it's a duplicate. – deceze May 16 '19 at 09:01
  • What have you tried to debug that problem? – Nico Haase May 16 '19 at 09:15

2 Answers2

0

your're displaying the error if the email is not used (there's no user with this email) if (mysqli_num_rows($res_e) == 0) {

kejsu
  • 384
  • 2
  • 5
0

Thanks for the comments, I noticed that I had a line of code missing:

$rws = $res_e->fetch_assoc();

And I changed the if statement to:

if ($rws == FALSE )

This has resolved my question. Thanks again.

Valikahn
  • 23
  • 2