I am creating a login script and I need to check that the username and e-mail don't current exist in the database otherwise it will print an error. I've tried the following but it's not working:

//Create Username Array
$SQL = "SELECT Username from user"
$Result = mysql_query($SQL);
$Array = mysql_fetch_array($Result);

//Check Username
if ($Username = $Array) {$errormessage = "Sorry, the username $Username is already in use.";}

else {

//Check Password
if ($Password != $RePassword) {$errormessage = "$FName likes it in the butthole, hence why their password doesn't match. Don't worry; however, we've disptached our butt elves to $Addr_Street $Addr_City, $Addr_State $Addr_Zip to remedy the problem";}

else {

Note: I've redacted the Insert statements that follow this ELSE statement

Any tips on what I should be doing instead? Also, is the nested IF statement the best way to go about doing this?

Dani AI

Generated

Quick summary and the real fixes (short, practical):

The immediate reason your INSERT kept running was control flow: the checks were separate IFs, so unless one of them halted execution (you used die()), the script continued to the INSERT. die() "works" because it halts the whole script, but the correct pattern is to collect validation errors and only run the INSERT when there are none. correctly flagged the = vs == and array-vs-value issues; ’s while loop overwrote $exist_username/$exist_email (so it only reflected the last row); ’s single-SELECT-WHERE idea is the right direction.

Use modern, safe building blocks

  • Stop using the old mysql_* extension — it was deprecated and removed from PHP; use PDO or MySQLi instead. (php.net)
  • Use prepared statements to avoid SQL injection (PDO prepared statements or mysqli). (php.net)
  • Hash passwords with password_hash() and verify with password_verify() — never store plaintext. (php.net)

Minimal pattern to follow (example — check first, then insert only if no errors):

// (assume $pdo is a PDO instance, inputs are validated/sanitized)
$stmt = $pdo->prepare('SELECT Username, Email FROM user WHERE Username = :u OR Email = :e LIMIT 1');
$stmt->execute([':u'=>$username, ':e'=>$email]);
$found = $stmt->fetch(PDO::FETCH_ASSOC);

$errors = [];
if ($found) {
  if (strcasecmp($found['Username'],$username)===0) $errors[] = 'Username taken';
  if (strcasecmp($found['Email'],$email)===0) $errors[] = 'Email already used';
}
if ($password !== $repassword) $errors[] = 'Passwords do not match';

if ($errors) {
  // return/show errors and do NOT insert
} else {
  $hash = password_hash($password, PASSWORD_DEFAULT);
  // prepared INSERT here
}

Final guards and testing
Enforce uniqueness at the database level with UNIQUE indexes (username/email) so duplicates can’t slip in under race conditions; then handle duplicate-key errors gracefully in your app. (dev.mysql.com)

Troubleshooting tips: test the SELECT statement separately, log SQL errors (use exceptions/E_MODE), and avoid die() in production — control logic and proper exception handling are cleaner and safer.

Recommended Answers

All 8 Replies

On line 7 you are using = instead of == but the problem is more than that. You can't compare a field to an array. You need to check against a specific element of the array, something like the following:

if ($username == $array['username']) {
     ...

Ok, so I updated it as follows but it's still not working, any ideas? :confused:

//Create Username Array
$SQL = "SELECT Username from user"
$Result = mysql_query($SQL);
$Array = mysql_fetch_array($Result);

//Check Username
if ($Username == $Array['Username']) {$errormessage = "Sorry, the username you have chosen ($Username) is already in use";}

else {

Anyway are you creating Log in script or a Sign up script?
But anyway, try this Jrotunda. (taga pinas ka ba?)

<?php
//maybe your need here something like...
$input_username = $_POST['username']; // user input. This is the value that will be check if already exist in the DB
$input_email = $_POST['email'];        // user input. This is the value that will be check if already exist in the DB
$SQL = mysql_query("SELECT Username from user");
while($result = mysql_fetch_array($SQL))
{
  $exist_username = $result['Username']'
  $exist_email = $result['Email']'
}

if($input_username == $exist_username || $input_email == $exit_email)
{
  echo "$input_username and/or $input_email already exist/used";
}

 
else
{

}
?>

It's a registration script for a new user. I modified your code a little bit (just changed some of the variable names as some of them are already set earlier in the code from the $_POST part but it's still not generating the error.

$SQL = mysql_query("SELECT Username,Email from user");
while($result = mysql_fetch_array($SQL))
{
  $exist_username = $result['Username'];
  $exist_email = $result['Email'];
}
 
if($Username == $exist_username || $Email == $exist_email)
{
  echo ("$Username and/or $Email already exist/used");
}

You can do the checking in the SQL statement itself.

Change $username and $email to the $_POST variable names you are using.
And change the column names or table name if they are different

$SQL = mysql_query("SELECT Username, Email from user WHERE Username = '$username' OR Email = '$email'");
 
if(mysql_num_rows($SQL) >= 1)
{
  echo ("$Username and/or $Email already exist/used");
}

You may want to test the SQL statement externally to debug..

Javvy, thanks for this, it's very, very close to what I am trying to do. I've broken the code up into two district SQL statements so that I can show a different error for each. I've noticed; however, that even when it's displaying the error message, it's still creating the record in the DB. Am I missing something here??? :confused:

//Check Username
$SQL = mysql_query("SELECT Username from user WHERE Username = '$Username'");
 
if(mysql_num_rows($SQL) >= 1)
{
  echo ("Sorry but the username you have selected ($Username) is already in use. Please select another username.");
}


//Check Email
$SQL = mysql_query("SELECT Email from user WHERE Email = '$Email'");
 
if(mysql_num_rows($SQL) >= 1)
{
  echo ("Sorry but the e-mail you entered ($Email) is already being used by another user.");
}


//Check Password
if ($Password != $RePassword) {$errormessage = "$FName likes it in the butthole, hence why their password doesn't match. Don't worry; however, we've disptached our butt elves to $Addr_Street $Addr_City, $Addr_State $Addr_Zip to remedy the problem";}

else {
	

//Create sql Statement Variable
$SQL = "INSERT INTO user VALUES ('NULL','$Username','$Password','$FName','$LName','$Email','$Addr_Street','$Addr_City','$Addr_State','$Addr_Zip',Now(),'NULL','NULL')";

//Insert Entry
if (!mysql_query($SQL))
  {
  die('Error: ' . mysql_error());
  }

I actually figured it out. In the example you provided (and the modified one above) if you change the echo to die it kills the rest of the process which prevents it from being created in the DB. Thanks again for the help Javvy! :)

You're welcome. The main problem is that the errors checking are on different IF-ELSE statement. So according to your code, the data will still insert even if same username/email exists. As long as the password matches.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.