Jump to content

If username exsists not working


slj90

Recommended Posts

<?php
include 'connect.php';

$username = 'Sam';

$result = mysql_query("SELECT * FROM users WHERE user_username = $username");
if(mysql_num_rows($result) == 0) {

 echo "available";
 }else{
  echo "not-available";
 }
?>

What could be wrong here?

It says that the username is available when it has already been taken.

 

Thanks,

Link to comment
https://forums.phpfreaks.com/topic/288121-if-username-exsists-not-working/
Share on other sites

Use mysql_error to find out why your query failed.

 

Also, stop using the mysql_* functions and learn about PDO or mysqli (or both) and the prepared statements they offer instead. They're faster and easier and safer. Because what you have now has a big, glaring vulnerability that will let people completely ruin your site if they wanted.

Hi,

 

note that the approach itself is incorrect: If a name isn't taken yet and two users ask for it at the same time, they're both allowed to have it. That's because there's a gap between the check and the action. While the name may not have been taken when you've checked, it may very well be taken when you insert the new row.

 

Unique values must be enforced at database level with a UNIQUE constraint. In your application, simply try to insert the row, and if it fails due to a violation of the constraint, you know that the username is already taken.This also lets you get rid of the extra query.

 

When you've chosen your database extension (I strongly recommend PDO instead of MySQLi), we can show you how to do it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.