Idk Idk - 3 years ago 135
MySQL Question

Making sure neither email nor username is taken already

So I am trying to make sure both the entered email and the entered username isn't already taken. I'm not sure why it's not working, I've only managed to have 1 work at a time.

session_start();
$con = mysqli_connect('localhost','root','');


-

$Email = $_POST['email'];
$Username = $_POST['username'];


-

$sqltwo = "SELECT Username FROM user WHERE `Username`='$Username'";
$resulttwo = $con->query($sqltwo);

if ($resulttwo->num_rows == 0) {
$UsernameTaken = false;
} else {
$_SESSION['usravailability'] = "Username already taken." ;
header ('location: index');
}

$sqlthree = "SELECT Email FROM user WHERE `Email`='$Email'";
$resultthree = $con->query($sqlthree);

if ($resultthree->num_rows == 0) {
$EmailTaken = false;
} else {
$_SESSION['emlavailability'] = "Username already taken." ;
header ('location: index');
}


if ($UsernameTaken == false && $EmailTaken == false) {
echo 'not taken;
} else {
echo 'taken';
}


I've also tried with

if ($UsernameTaken == false || $EmailTaken == false) {
echo 'not taken;
} else {
echo 'taken';
}


which didn't work either. I'm probably doing something very wrong, but I have no idea what.

Answer Source

A simpler version in my opinion would be to have one sql statement:

$sqlquery = "SELECT Username, Email FROM user WHERE `Username`='$Username` OR `Email`='$Username`";

Then check if any rows are found and store that value in a new variable (ex. alreadyExists).

For the message, if any rows are found, check if the $Username variable matches the username in the row, then output a message that "the username already exists", else if the email matches, output that "the email already exists".

Like this you'll just have one query, reducing connections to the database and only one variable to check, 'alreadyExists'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download