简体   繁体   中英

Website and Database: Check if username exists

I've been searching on Google for 2 weeks now and nothing is working. All I want to know is 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 an add the username anyway, causing my table to have duplicates of the same username. I have tried many codes and many methods. Been using Mysqli since that is what we are supposed to use now. I could give you any number of methods I have tried but here is the latest one I am trying again for the 100th time. Please be ware, that 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. Another note to add, my database login info is stored on a seperate php file named "credentials.php". Thanks in advanced. CODE:

<?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();        
            }
        }
    }
}
?>

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

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.

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'");

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.

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();

}
}
}
}
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM