Yazrihm Doe Yazrihm Doe - 3 months ago 8
PHP Question

PHP username already exists, when it doesn't

I've checked many threads about my problem, but it still won't work.

When I enter username, which doesn't exist, it will throw the username has been created yet. But, when I enter an username already registered in my db, it still register.

Here is my php/html page for register :

$error = false;
if(isset($_POST['signup'])) {

$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);

$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";
$query = mysqli_query($sql);
if(mysql_num_rows($query)){
$error = true;
$ckname_error = "Nom d'utilisateur déjà enregistré!";
} else { unset($ckname_error); }


if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,mail,password,rank) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "', 'user' )")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
header("Location: login.php");
} else {
$errormsg = "Error in registering...Please try again later!";
}
}

Answer

You're getting unreliable results because you're mixing mysqli_ with mysql_ functions.

1. Change:

$sql = "SELECT name FROM users WHERE name='".mysql_real_escape_string($name)."'";

to:

$sql = "SELECT name FROM users WHERE name='$name'";

2. Change

$query = mysqli_query($sql);

to:

$query = mysqli_query($con,$sql);

3. Change

if(mysql_num_rows($query))

to:

if(mysqli_num_rows($query))