1

I want to know how to check if the given username exists in my MySQL database table. Table name is users. But it seems to bypass my if statement, and go right ahead and add the username anyway, causing my table to have duplicates of the same username.

I have been using Mysqli since that is what we are supposed to use now. Here is the latest method I have tried. I know this isn't quite prepared from defending against SQL injection, I am not worried about that just yet. I am just trying to get this thing to work first, then I will add the security.

My database login info is stored on a separate php file named "credentials.php".

<?php
$password1 = ($_POST['pass1']);
$password2 = ($_POST['pass2']);
$firstname = ($_POST['fname']);
$lastname = ($_POST['lname']);
$username = ($_POST['user']);
$email = ($_POST['email']);     

/*
include_once 'credentials.php';
$dbhandle = new mysqli($db_hostname, $db_username, $db_password, $db_database); 
 */
// Check if any fields are empty
if (empty($_POST['fname']) or empty($_POST['lname']) or empty($_POST['user']) or empty($_POST['email']) or empty($_POST['pass1']) or empty($_POST['pass2'])){
?>
<div class="ERRORBOX">
<?php
 // Empty Fields ERROR
    echo "You must enter data into ALL of the fields to register. Please try again.";
    header( "refresh:5;url=../index.php" );
?>
    <p>You will be redirected in <span id="counter">5</span> second(s).</p>
    <script type="text/javascript">
    function countdown() {
        var i = document.getElementById('counter');
        if (parseInt(i.innerHTML)<=0) {
            location.href = 'login.php';
        }
        i.innerHTML = parseInt(i.innerHTML)-1;
    }
    setInterval(function(){ countdown(); },1000);
    </script>
</div>
<?php
} else {
    // Check if passwords match
    if ($password1 !== $password2) {
    ?>
    <div class="ERRORBOX">
    <?php
    // Password mismatch ERROR
        echo "You entered two different passwords! Please try again.";
        header( "refresh:5;url=../index.php" );
    ?>
        <p>You will be redirected in <span id="counter">5</span> second(s).</p>
        <script type="text/javascript">
        function countdown() {
            var i = document.getElementById('counter');
            if (parseInt(i.innerHTML)<=0) {
                location.href = 'login.php';
            }
            i.innerHTML = parseInt(i.innerHTML)-1;
        }
        setInterval(function(){ countdown(); },1000);
        </script>
    </div>
    <?php
    } else {    
        // Create connection
        include_once 'credentials.php';
        $conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        // Check if username exists <<<THIS IS WHERE I AM HAVING TROUBLE<<<<<
        $username = ($_POST['user']);
        
        $query = mysqli_query("SELECT * FROM users WHERE username='$username'");
        if(mysqli_num_rows($query) > 0){
            echo "That username already exists.";   
            $conn->close();
        }
        else{
            //IT JUST SKIPS THE CODE ABOVE AND GOES STRAIGHT TO THE ONE BELOW
            $firstname = ($_POST['fname']);
            $lastname = ($_POST['lname']);
            $username = ($_POST['user']);
            $email = ($_POST['email']);
            $password = ($_POST['pass1']);
            $ipaddress = $_SERVER['REMOTE_ADDR'];  
        
            // Create connection
            include_once 'credentials.php';
            $conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);        
                $sql = "INSERT INTO users (`id`, `username`, `password`, `sign_up_date`, `email`, `email_activation`, `permit`, `status`, `first_name`, `last_name`, `dob`, `ipv4`) VALUES (NULL, '$username', '$password', NOW(), '$email', '0', 'c', 'a', '$firstname', '$lastname', '1985-01-01', '$ipaddress')";
                
                if ($conn->query($sql) === TRUE) {
                    header('Location: ../success.php');
                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                }        
                $conn->close();        
            }
        }
    }
}
?>
5
  • 2
    Don't check if the username already exists, simply put a UNIQUE constraint in your database for the username column. Then attempt to insert, if $conn->error() is set then you know that the username already exists. Commented Jun 6, 2016 at 6:27
  • I don't understand. Commented Jun 6, 2016 at 6:28
  • If you manually run the query on the db, are you getting results for this? SELECT * FROM users WHERE username='$username' for the exact same username you are trying to use? Commented Jun 6, 2016 at 6:34
  • Ok I see about the unique contstraint. So that locks any column you select for it. Thats cool. Wish I knew about that before. Thanks. So, I just completely took out the entire check if username exists block. But now, instead of passing forward to the insert code block, it just displays a blank page. Commented Jun 6, 2016 at 6:38
  • use $query = mysqli_query("SELECT * FROM users WHERE username='".$username."'"); Commented Jun 6, 2016 at 6:38

5 Answers 5

2

First of all when you want the value of a row in the database table to appear only once you need to specify that column as UNIQUE. So start by altering the users table like this:

ALTER TABLE users CHANGE COLUMN username username VARCHAR(255) NOT NULL UNIQUE;

After you've done that, if your script tries to insert a row in the database that contains a username that has already been used, that row won't insert and you won't have duplicates. But that's not enough, you need a way to inform the user that the username they want is already in use, so that's where your PHP script comes in.

Your script isn't working because you call mysqli_query without the database connection object.

There are two ways you can call mysql_query:

  • Using the procedural style: mysqli_query($conn, "SELECT * FROM users WHERE username='$username'");
  • Going OOP-style: $conn->query("SELECT * FROM users WHERE username='$username'");

You call mysqli_query in a procedural style without giving it a connection object. Change it to one of the above and it will work

Sign up to request clarification or add additional context in comments.

5 Comments

mysqli_query is designed to the called with the query as the first and only param as well.
I did. See this mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) In this, you can use $query as the only mandatory param.
@phreakv6 That's OOP-style, the one I mention in the second bullet. It says: mysqli::query that's a scope resolution operator meaning the query method of an instance of the mysqli class. This is the prototype for the procedural style: mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) it needs a link
Either way, use prepared statements
@Strawberry I agree, it's just that OP said he knows about SQL Injection and what he needs to do, so I assumed he just wants a reason why his code is not working
2

I would highly recommend just adding a UNIQUE constraint to your table column.

Run the following query in MySQL:

ALTER TABLE users ADD CONSTRAINT ux_username UNIQUE (username)

Now don't do any checks, simply insert your new user and check $conn->error().

$sql = "INSERT INTO users (`id`, `username`, `password`, `sign_up_date`, `email`, `email_activation`, `permit`, `status`, `first_name`, `last_name`, `dob`, `ipv4`) VALUES (NULL, ?, ?, NOW(), ?, '0', 'c', 'a', ?, ?, '1985-01-01', ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $username, $password, $email, $firstname, $lastname, $ipaddress);
$stmt->execute();

if (empty($conn->error())) {
    header('Location: ../success.php');
    exit; //remember to exit after redirections
} else {
    echo 'Username already exists.';
}

Also I changed your code to properly insert the data. Inserting raw user input is dangerous as there might be a loose single quote or semicolon.

Comments

0

Add a unique constraint to the table.

ALTER TABLE `users` ADD UNIQUE(`username`);

This will prevent the duplicate inserts. You should still try to figure out why you are having issues with that mysqli_num_rows. I suggest you run the query manually and see if it returns results.

1 Comment

no matter what i run in the query, any block of code, i get this exact same message: MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'include_once 'credentials.php'' at line 1
0

You have used mysqli_query in wrong manner either use

$query = mysqli_query($conn,"SELECT * FROM test WHERE username='$username'");

or use

$query = $conn->query("SELECT * FROM test WHERE username='$username'");

Comments

-1

FOUND A SOLUTION. I think the guy who came up with the solution deleted his answer. So I will post it here: (By the way, thanks everyone. Your answers were helpful too.)

<?php

$password1 = ($_POST['pass1']);
$password2 = ($_POST['pass2']);
$firstname = ($_POST['fname']);
$lastname = ($_POST['lname']);
$username = ($_POST['user']);
$email = ($_POST['email']);




// Check if any fields are empty
if (empty($_POST['fname']) or empty($_POST['lname']) or empty($_POST['user']) or empty($_POST['email']) or empty($_POST['pass1']) or empty($_POST['pass2'])){
 ?><div class="ERRORBOX"><?php
 // Empty Fields ERROR
echo "You must enter data into ALL of the fields to register. Please try again.";
header( "refresh:5;url=../index.php" );
 ?>
<p>You will be redirected in <span id="counter">5</span> second(s).</p>
<script type="text/javascript">
function countdown() {
    var i = document.getElementById('counter');
    if (parseInt(i.innerHTML)<=0) {
        location.href = 'login.php';
    }
    i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
</div>
<?php


} else {
// Check if passwords match
if ($password1 !== $password2) {
?><div class="ERRORBOX"><?php
// Password mismatch ERROR
    echo "You entered two different passwords! Please try again.";
header( "refresh:5;url=../index.php" );
?>
<p>You will be redirected in <span id="counter">5</span> second(s).</p>
<script type="text/javascript">
function countdown() {
    var i = document.getElementById('counter');
    if (parseInt(i.innerHTML)<=0) {
        location.href = 'login.php';
    }
    i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
</div>
<?php



} else {    

 // Create connection
          include_once 'credentials.php';
          $conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
          // Check connection
          if ($conn->connect_error) {
             die("Connection failed: " . $conn->connect_error);
          }


          // Check if username exists 
          $username = ($_POST['user']);
          $qry="SELECT * FROM users WHERE username='".$username."'"; 
          $query = mysqli_query($conn, $qry);
          if(mysqli_num_rows($query) > 0){
?><div class="ERRORBOX"><?php
               echo "That username already exists.";
?></div><?php


}else{

          // Check if email exists 
          $email= ($_POST['email']);
          $qry="SELECT * FROM users WHERE email='".$email."'"; 
          $query = mysqli_query($conn, $qry);
          if(mysqli_num_rows($query) > 0){
?><div class="ERRORBOX"><?php
               echo "That email is already registered.";
?></div><?php
               $conn->close();




 }else{

$firstname = ($_POST['fname']);
 $lastname = ($_POST['lname']);
 $username = ($_POST['user']);
 $email = ($_POST['email']);
 $password = ($_POST['pass1']);
$ipaddress = $_SERVER['REMOTE_ADDR']; 

// Create connection
include_once 'credentials.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

 }else{

$sql = "INSERT INTO users (`id`, `username`, `password`, `sign_up_date`, `email`, `email_activation`, `permit`, `status`, `first_name`, `last_name`, `dob`, `ipv4`) VALUES (NULL, '$username', '$password', NOW(), '$email', '0', 'c', 'a', '$firstname', '$lastname', '1985-01-01', '$ipaddress')";


if ($conn->query($sql) === TRUE) {
    header('Location: ../success.php');
exit;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

}
}
}
}
}

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.