-1

I'm trying to find if the username a user enters hasn't already been used by others, but it doesn't seem to work. Here's the code. I don't know what else to put.

   require 'database.php';

   $password = $_POST['password'];
   $fname = $_POST['fname'];
   $lname = $_POST['lname'];
   $username = $_POST['username'];
   $email = $_POST['email'];

   $message = '';
   if ($password === ""){
       $message = "<div class='errormsg'>Oops! Must've missed a spot!</div>";
   }
   else if ($fname === ""){
       $message = "<div class='errormsg'>Oops! Must've missed a spot!</div>";
   }
   else if ($lname === ""){
       $message = "<div class='errormsg'>Oops! Must've missed a spot!</div>";
   }
   else if ($email === ""){
       $message = "<div class='errormsg'>Oops! Must've missed a spot!</div>";
   }
   else if ($username === ""){
       $message = "<div class='errormsg'>Oops! Must've missed a spot!</div>";
   }
   $query = mysql_query("SELECT username FROM users WHERE username='".$username."'");

   if (mysql_num_rows($query) != 0)
   {
       $message = "<div class='errormsg'>Username already exists!</div>";
   }
  • Enable error-reporting and check your logs, it'll tell you what to look for. `error_reporting(E_ALL);` `ini_set('display_errors', 1);` [`mysql_error`](http://php.net/manual/en/function.mysql-error.php) – Qirel Nov 20 '16 at 04:40
  • 2
    `mysql_*` functions are deprecated since PHP 5.5 (and **removed entirely** in PHP 7) and you should [stop using them](http://stackoverflow.com/q/12859942) if you can. You should choose another API that allows you to use [prepared statements](http://stackoverflow.com/q/60174/) (which you *really should* when dealing with variables), like `mysqli_*` or PDO - see [choosing an API](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Qirel Nov 20 '16 at 04:40
  • You should first make your username column in your mysql table unique as a backup. – Rasclatt Nov 20 '16 at 04:40
  • Then use a function to fetch the count that is human-readable, something like `function userExists($con,$username) {...ect }` This would be used in an `if` statement like `if(!userExists($con,$_POST['username'])) { //do stuff }`. Try breaking your code into specific parts. Make sure you are using the latest database library as mentioned and not mixing raw user input into your statement. – Rasclatt Nov 20 '16 at 04:44

1 Answers1

1

Try to use this function to check for existing users with that name:

function userExists($input) {
  $count = mysql_query("SELECT COUNT(*) FROM users WHERE username='".$input."'");
  if ($count > 0) $output = "User already exists";
  return $output;
}

You can try it like that then to check:

if (userExists($username)) { ... }

But consider stop using mysql_ in the future since it's deprecated.

AlexioVay
  • 4,338
  • 2
  • 31
  • 49