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.
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'
A few problems I see that can improve your script.
1st - Select a database before running your query
2nd - Sanitize the user input with prepared statements, or bare minimum use mysqli_real_escape_string.
3rd - As @CliveCiappara wrote in his answer, one query will suffice.
4th - Add an ' in your echo ( echo 'not taken'; )
session_start();
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$Email = $con->mysqli_real_escape_string($_POST['email']);
$Username = $con->mysqli_real_escape_string($_POST['username']);
$q = "SELECT Username, Email
FROM user
WHERE `Username`='$Username'
OR `Email`='$Email'";
$r = $con->query("$q");
echo ($r->num_rows === 0) ? "Not Taken" : "Taken";
You seem to be missing a '
after not taken
(not properly terminating your string). Could this be related to your problem?