How can I make this PDO mysql query with if statements work correctly?
I am building a web site from scratch for a little project.
I have stumbled across a little problem of mine and have scratched my head over it to no avail! Here is my code;
else if (isset($_POST['hidden']) && $_POST['hidden'] = 1) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_POST['username']));
if ($q -> rowCount() > 0) {
echo 'USERNAME TAKEN<br />';
}
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_POST['email']));
if ($q -> rowCount() > 0) {
echo 'EMAIL TAKEN<br />';
}
else {
$q = $dbc -> prepare("INSERT INTO accounts (fname, lname, email, password, username, gender) VALUES (?, ?, ?, ?, ?, ?)"); $q -> execute(array($_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['password'], $_POST['username'], $_POST['gender']));
echo 'YOUR ACCOUNT NEEDS ACTIVATING';
}
}
Now my problem lies with checking if the username and email are already taken.
I have one if statement for checking the username.
I have one if statement for checking the email.
And I have one else statement for inserting the data into the mysql table if all is good.
The problem I have is that is the username is the same, and the email is not then the else statement still fires, I know it does as I have on my html document
'USERNAME TAKEN' & 'ACCOUNT NEEDS ACTIVATING'
I thought about putting them in 'else if' statements but I need both the username and email to work together not if one wo开发者_如何学JAVArks then not the other. Any ideas??
Thanks in advance.
Is this what you're looking for?
else if (isset($_POST['hidden']) && $_POST['hidden'] = 1) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_POST['username']));
$username_taken = $q->rowCount() > 0;
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_POST['email']));
$email_taken = $q->rowCount() > 0;
if ($username_taken || $email_taken) {
if ($username_taken) {
echo 'USERNAME TAKEN<br />';
}
if ($email_taken) {
echo 'EMAIL TAKEN<br />';
}
}
else {
$q = $dbc -> prepare("INSERT INTO accounts (fname, lname, email, password, username, gender) VALUES (?, ?, ?, ?, ?, ?)"); $q -> execute(array($_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['password'], $_POST['username'], $_POST['gender']));
echo 'YOUR ACCOUNT NEEDS ACTIVATING';
}
}
精彩评论