Directing user to a page or another (PHP and MysQL) - php

I am creating a site where invited users will be directed to a register once their email is validated against a master list of users and (2) returning users will be directed to a different page once validated against a master list of users. Initially the master list of users will only have email addresses for the invited users. Upon registration, users will enter the rest of the information, including First Name (fname).
What I need to do with this piece of code is check if the first name is NULL, if so direct user to "registration.html"; whereas if a first name is present for that user then the user should be directed to "overview.html".
My code is clearly not working properly, as regardless of fname being NULL or XYZ users are directed to "overview.html".
$query = "SELECT email, fname FROM registration WHERE email='$email'";
if (fname = "NULL") {
header('location: registration.html');
} else {
header('location: overview.html');
}
Thanks for your help!

I'm assuming you didn't paste the whole code here. How did you fetch the row?
One thing I can point out though, in PHP = is assignment.You want to use == which is the comparison operator.
Also, unquote "NULL", as you're currently comparing it to a string 'null'.
Hope that solves it.
EDIT: seeing your other comments, here's what the code should look like, assuming you have the email stored in a variable called $email and a PDO connection stored in $dbc.
$q = "SELECT email, fname FROM registration WHERE email = ?";
$stmt = $dbc->prepare($q);
$stmt->execute(array($email));
if($stmt->rowCount() == 1){ //you probably have unique email accounts
$row = $stmt->fetch();
if (is_null($row['fname'])) {
header('location: registration.html');
} else {
header('location: overview.html');
}
}

Related

How to use php to search if element already exists in mysql db

I've got a website and when a user registers I want to check, if the entered email has already been used to register another account.
database: users
row: email
new email: $email_register
$result = $pdo->prepare("IF email_register = ? IN email FROM users $same = TRUE");
$result->execute(array($email_register));
$user = $result->fetch();
if($same == TRUE)
{
echo email already used;
}
else
{
#continue registration process
}
I want a way to know if the email is already in the db, and if it is, for the user to be sent back to the registration page with an error message (error code transmitted via header).
Assuming that users should not have more than one account per email, an easy approach is to make the email column a unique key (or primary key) in the users table. This prevents an email being used more than once.
Try this way
// check if email is taken already
$stmt = $pdo->prepare("SELECT email FROM users WHERE email_register = :email");
$stmt->execute([
'email_register ' => $email
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (isset($user) && !empty($user)){
// Username already taken
echo "email already used";
}else{
//redirect to registration process
}
There is no need for IF in the SQL query. Just write simple select statement like:
Select email from users where email = 'example#example.com';
if query return and result it means the email is already in database if not then you can continue to the registration process.
if($exist)
{
return false; or you redirect to registration page whatever you want to do.
}
#continue registration process

Create an exception in PHP and PDO to prevent duplicates

Hello Stackoverflow community,
I'm starting to work with PDO soon. I have a trivial question that I do not know how to solve. So, let me know if you guys can help me.
I have a form that aims to update data from a user account in a member space. This form has three fields "Last Name", "Name" and "E-mail".
I don't want that the user register and existing e-mail. However, if the user does not want to update their email and only wants to change the "Last Name" and "Name" fields, the PHP code must allow updating the records in the database.
I created a function to process the form. It is able to prevent the insertion of duplicate records, but it has a problem. If the user does not want to update their email, the function returns that there is already an equal email in the database. In fact, email already exists, so I would like to know how to implement this exception in my code to allow it to update the records when the user does not want to change their e-mail?
Below the function:
function update_admin_profile() {
session_start();
if (isset($_SESSION['id']) AND isset($_SESSION['login'])) {
// get the session variables for another propouse.
$id = $_SESSION['id'];
$pseudo = $_SESSION['login'];
// p - It's the URL parameter. anti_sql_injection is a function to check the parameter.
$p = anti_sql_injection($_GET['p']);
if (isset($_POST['last_name']) AND isset($_POST['name']) AND isset($_POST['email'])) {
$bdd = connexion_bdd();
$query = $bdd->prepare('SELECT * FROM tbl__administrators WHERE email = :email');
$query->execute(array('email' => htmlspecialchars($_POST['email'])));
$count=$query->rowCount();
if ($count == 0 ) {
$update = $bdd->prepare('UPDATE tbl__administrators SET last_name = :last_name, name = :name, email = :email WHERE id = ' . $p);
$update->execute(array(
'last_name' => htmlspecialchars($_POST['last_name']),
'name' => htmlspecialchars($_POST['name']),
'email' => htmlspecialchars($_POST['email'])
));
//The profile was updated.
header('Location: notify.php?m=49');
} else {
//The e-mail already exists!
header('Location: notify.php?m=48');
}
} else {
//Please fill in all fields
header('Location: notify.php?m=41');
}
} else {
//You session is expired. You will be disconnected now. Please, perform the login again and repeat this operation.
header('Location: notify.php?m=7');
}
}
Note: It's function works if I change the e-mail.
Thank you so much for your help.
Have nice day.
If the user does not want to update their email, the function returns that there is already an equal email in the database.
It's very simple. Just add another condition to exclude the current user from the query results
$query = $bdd->prepare('SELECT 1 FROM tbl__administrators WHERE email = ? and id != ?');
$query->execute(array($_POST['email'], $id));

MySQL multiple queries not working

Problem has been solved
I have created a form that processes the changing of user information from the admin side e.g. the admin changes a user's username and/or email. I am having trouble processing multiple queries.
For example, if the admin changes the username, the query works. If the admin changes the email address, the query works. But if the admin changes the username and email at the same time through the form then only the username changes.
Any ideas? I will submit my code but I will change variables for security reasons etc. Also, anything in capitals has been changed for security reasons. The code is all correct for each individual function because as I said, if I ONLY change the email, it works and actually changes. But if I change the username AND email, only the username will change despite the fact the email query runs and it echo's the email has been changed!
Also, it is worth noting that all of the fields e.g. username field and email field are part of one form that submits to one page.
if (isset($_POST['SUBMIT_BUTTON_PRESSED'])) {
//Gather all inputs from the form and sanitise it.
//REMOVED FOR SECURITY REASONS.
if($USERNAME_NEW != "") {
if($USERNAME_NEW == $CURRENT_USERNAME) {
echo "You have entered the username you are already using. Please enter a different username.";
} else {
$CHECK_USERNAME = "SELECT USERNAME_ROW FROM USERS_TABLE WHERE username='$USERNAME_NEW'";
$RUN_QUERY = mysqli_query($CONNECTION INFO, $CHECK_USERNAME);
$RESULT = mysqli_num_rows($RUN_QUERY);
if($RESULT > 0) {
echo "That username already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_username = true;
$USERNAME = $NEW_USERNAME; //NOT NEEDED BUT IT STILL WORKS
$THE_SQL_QUERY = "UPDATE USER_TABLE SET username='$USERNAME' WHERE username='$ORIGINAL USERNAME'";
$RUN_THIS_QUERY= mysqli_query($CONNECTION INFO, $THE_SQL_QUERY);
echo "The user's username has been changed to: ". $USERNAME;
}
}
}
if($EMAIL != "") {
if($EMAIL == $CURRENT_EMAIL) {
echo "You have entered the same email address to the one you are already using. Please enter a different email address.";
} else {
$CHECK_EMAIL = "SELECT USERS_EMAIL FROM USER_TABLE WHERE username='$USER'";
$CHECK_EMAIL_QUERY = mysqli_query($CONNECTION_INFO, $CHECK_EMAIL);
$RESULT = mysqli_num_rows($CHECK_EMAIL_QUERY);
if($RESULT > 0) {
echo "That email already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_email = true;
$THE_NEW_EMAIL = $FINAL_EMAIL_THING; // AGAIN NOT NEEDED BUT STILL WORKS
$THE_SQL= "UPDATE USER_TABLE SET USER_EMAIL='$EMAIL' WHERE username='$USER' LIMIT 1"; // REMOVED THE LIMIT 1, STILL DOESN'T WORK
$RUN_THIS_QUERY = mysqli_query($CONNECTION, $THE_SQL);
if($RUN_THIS_QUERY) {
echo "The user's email has been changed."; // EVEN WHEN BOTH FIELDS ARE SUBMITTED THIS WORKS SO THE QUERY IS RUNNING BUT THE EMAIL DOESN'T CHANGE
}
}
}
}
Thanks for the help! Also, no un-witty remarks about how my question is structured etc. because I don't care to be honest. I just want this code working to be honest because I've been working on it for a while. This may be something simple or I might be using the wrong approach for this type of form submission.
Remember: THIS CODE DOES WORK WHEN I SUBMIT EACH FIELD SEPARATELY!
Its very hard to figure out as you are not producing the real code.
I think you have missed something here.
As you are using USER_NAME as key in the SQL's, make sure that you are using the updated username in the second sets of SQL (to update the email) as they are already replaced by the first SQL.
And there is no security risk while showing your codes snippets to someone else. Hide only the username/passwords or Identities. :)

Cross-referencing MySQL entries

This is the first time I've used this place, so forgive me if I'm being completely stupid here.
Basically, I'm coding a system where User A signs an institution up to the service, receiving a verification code for members of that institution, and then User B, part of that institution, enters the unique verification code to register.
The code for signing up User A works - it assigns a unique auto-incrementing ID (sid, or uid in the database) and a random verification code (verification) - and I am satisfied with it (aside from security concerns, but I need to learn how to deal with those).
My problem is that whenever anyone tries to sign up as a User B, and use the verification code, the system rejects it, and says that the verification code does not match the one under that particular sid. I have a feeling it's to do with the code I am using to look up the verification id, but I don't know where I'm going wrong.
The current code:
$getsid = mysql_query(
"SELECT *
FROM schools
WHERE uid='$sid'");
while($row = mysql_fetch_array($getsid)) {
$origver = $row['verification'];
}
if ($pwd != $conf) {
header('Location: register.php?error=1');
}
elseif ($ver != $origver) {
header('Location: register.php?error=2');
}
else {
Just for further information, $ver is the verification number entered by User B, which is meant to match with $origver.
It seems you must add some debug statements, in order to see what's going on
var_dump($sid);
$getsid = mysql_query(
"SELECT *
FROM schools
WHERE uid='$sid'");
while($row = mysql_fetch_array($getsid)) {
var_dump($row);
$origver = $row['verification'];
}
var_dump($pwd, $conf);
if ($pwd != $conf) {
header('Location: register.php?error=1');

mysql_affected_rows() work-around?

I'm using this code as part of an email confirmation script. It works great, except I can't figure out a way to distinguish between when somebody has provided an invalid email address vs when they have simply refreshed the page (ie. already confirmed their account). The only think I can think of is putting a time stamp field in the users table that always gets updated, but I'm hoping there is a better way. I thought REPLACE would do the trick, but, while email is unique, it is not the primary key.
if (isset ($email, $token, $correctToken)){
$success = FALSE; //Set the $success variable so that we don't get an error when testing for it later
if ($token == $correctToken) {
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE email = '$email'");
if (mysql_affected_rows() == 1) {
echo "Thank you! Your email address is confirmed and your account is actived.";
$success = TRUE;
}
}
if (!$success) {
echo "There was a problem with the confirmation. Try the link in your email again or contact us at Support#WiseRenters.com";
// Send email to admin to notify of error
exit;
}
}
Thanks in advance for the advice!
Billy
EDIT: The $email and $token variables are provided through $_GET or $_POST, in case that wasn't obvious.
A redirection would stop them from refreshing - but what if they click the link in their email again?
You should check if the current user is activated or not.
$sql = "SELECT id, conf FROM users WHERE email = '{$email}'";
$exec = mysql_query($sql) or die(mysql_error());
list( $id, $conf ) = mysql_fetch_row($exec);
if( $conf ) {
// Redirect them to their profile with a message saying "your account has already been activated"
header("Location: /profile?already_activated");
exit;
}
// your code
$confirm = mysql_query("UPDATE users
SET conf = 'TRUE'
WHERE id = '{$id}'");
In response to your comment:
Keep in mind this will only add an additional query for a user who has not activated yet. If they have activated then the redirect occurs and the page is still running only 1 query.
To optimize this a bit, you can select the user ID and confirmation status based on the email address. Then, if they do need to be activated, you can activate them based on user ID instead of email. Since an integer key is much faster, the combined time of the 2 queries will be about the same as the 1 query where you are updating based on a string column. I updated the code to reflect this.
Also, this page will probably not be accessed very frequently. Any optimizations from here would really be micro- and not really that helpful.
By the way I hope you are using mysql_real_escape_string on the email, and that conf is a boolean true/false not a string 'true'/'false'.

Categories