PHP forgot password - php

I am trying to create a forgot password page for the user in PHP but when I enter the code the page just reloads and nothing else happens . No errors nothing .
if($submit){
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$submit = $_POST['submit'];
$email_check = mysqli_query($conn ,"SELECT * FROM users WHERE email='" . $email. "'");
$count = mysqli_num_rows($email_check);
if($count != 0 ){
// generate a new password
$random = rand(72891, 92729);
$new_password = $random;
$email_password = $new_password;
$new_password = password_hash($new_password, PASSWORD_BCRYPT, array('cost' => 14));
$new_password = password_hash($new_password);
mysqli_query("update users set pw='" . $new_password. "' WHERE email='" . $email. "'");
$subject = "Login information";
$message = "Your password has been changed to $email_password";
$from = "From: example.me";
mail($email, $subject, $message, $from);
echo "Your new password has been sent to you";
} else {
echo"This email does not exists";
}
}

I will tell you exactly what is going on with your code here.
Part 1:
if($submit){
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$submit = $_POST['submit'];
$submit = $_POST['submit']; is assigned after your opening if($submit).
Result with error reporting: Undefined submit variable.
Part 2:
$new_password = password_hash($new_password, PASSWORD_BCRYPT, array('cost' => 14));
$new_password = password_hash($new_password);
You're trying to double hash which won't give you any added benefits and will also fail when trying to verify it later. What happened here is that the second one failed and shouldn't even be used at all.
Why did it fail? Because, it's missing a parameter.
Result:
Warning: password_hash() expects at least 2 parameters, 1 given in /path/to/file.php on line x
Added result: An empty password row (when the UPDATE happens. See "Part 3").
Part 3:
mysqli_query("update users set pw='" . $new_password. "' WHERE email='" . $email. "'");
The query doesn't contain a database connection for it.
Result:
Warning: mysqli_query() expects at least 2 parameters, 1 given in /path/to/file.php on line x
In regards to your variables and the connection API used is unknown, so you will have to make sure that you are using the same MySQL API to connect with, and that your variables and POST arrays contain values.
Error reporting will help you, as will checking for errors on the query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
Final notes:
Use a prepared statement instead, it's much safer
https://en.wikipedia.org/wiki/Prepared_statement
Also; you should let the user choose their own password in a reset with a unique/one time token and hash it "once", not twice and shouldn't be mailed their password and for a lot of reasons. This is best common practice. If the user's email account ever gets compromised and they haven't deleted the email containing their login password, then they are at risk in having their login account also being compromised.

$submit is not declared until after the validation of your if statement.
Validate using another variable. Good place to start is to check and see if $_POST is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST')
To email the password change
$message = "Your password has been changed to $email_password";
to
$message = "Your password has been changed to {$email_password}";
The password stored in the DB has been hashed twice. Remove
$new_password = password_hash($new_password);
The SQL needs to be executed to update the password hash in the database.
$sql = "update users set pw='" . $new_password. "' WHERE email='" . $email. "'";
if (mysqli_query($conn, $sql)) {
echo "Password updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);

You're testing for $submit but defining $submit inside of the test, so $submit likely isn't evaluating as true.
Try changing the outer if ($submit) to if (!empty($_POST))

Related

password_verify Always Returns False, even with proper variables used

My webpage starts with a login page, like many, and if the user has no account they can sign up. My sign up works and the users password they input is successfully hashed with password_hash and sent to the database. However, when trying to login, password_verify always returns false. Thinking I made a silly error when I originally made the hashed password, I echoed the variable I was using as the second parameter in password_verify. However, it was an exact match to the hash in the database. What could be the issue?? Shortened code is available below for both creating the password during sign up and checking the password while logging in.
CREATING HASHED PASSWORD
<?php
session_start();
require('db_credentials.php');
$inputUsername = $_POST['createUsername'] ? $_POST['createUsername'] : null;
$inputPassword = $_POST['createPassword'] ? $_POST['createPassword'] : null;
$vPassword = $_POST['verifyPassword'] ? $_POST['verifyPassword'] : null;
//protect database from corrupt user input
$inputUsername = $mysqli->real_escape_string($inputUsername);
$inputPassword = $mysqli->real_escape_string($inputPassword);
$vPassword = $mysqli->real_escape_string($vPassword);
//create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
$protectedPassword = password_hash($inputPassword, PASSWORD_DEFAULT);
//Check if the passwords match
if($inputPassword != $vPassword){
echo '<p style = "text-align: center;">Oops!The passwords you input did not match. Please try again.</p>';
session_write_close();
exit;
}
//Check for duplicate username
$query = "SELECT * FROM user_info WHERE username = ' ".$inputUsername." ' ";
$result = mysqli_query($mysqli, $query);
if(mysqli_num_rows($result) == 1) {
echo '<p style = "text-align: center;">Oops! That Username is already taken. <br>Please try a different one.</p>';
session_write_close();
exit;
}
//Username is not takin and the passwords match
else {
$sql = "INSERT INTO user_info (username, password) VALUES (' ".$inputUsername." ', ' ".$protectedPassword." ')";
echo '<p style = "text-align: center;">Success! You Have Made an Account!</p>';
if($mysqli->query($sql) === TRUE) {
session_write_close();
exit;
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
LOGGING IN
<?php
require('db_credentials.php');
$inputUsername = $_POST['username'] ? $_POST['username'] : null;
$inputPassword = $_POST['password'] ? $_POST['password'] : null;
//protect database from corrupt user input
$inputUsername = $mysqli->real_escape_string($inputUsername);
$inputPassword = $mysqli->real_escape_string($inputPassword);
$mysqli = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT * FROM user_info WHERE username = ' ".$inputUsername." ' ";
$result = $mysqli->query($query);
//check if username is in database. If it is, do the passwords match?
if($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
echo $row['password'] . "<br>"; //matches hash in database exactly
echo $inputPassword; //matches the password I type in. Which is same I used to sign up.
if(password_verify($inputPassword, $row['password'])){
header("Location: puzzlerMember.php"); //this never happens
exit;
}
}
echo '<p style = "text-align: center;">Oops! Your Username/Password is incorrect. Sign up if you do not have an account.</p>'; //this always happens
exit;
?>
Note: In the database, I have the password column set to VARCHAR(255).
I've looked at many of these questions which are similar, but they all seemed to have mistaken the length of their password in the database to be too short. If they did not, I tried the top answer of the solutions. I have absolutely no idea what is wrong.
If you can help, I thank you in advance.
You are escaping your password, as a result this changes the password from what it was. Instead of relying on escaping as a security measure (which in itself is a misconception), use prepared statements.
As per the comment below, a clarification is required it seems: You are escaping the password then hashing it, as a result what is stored in the db is not what the user passes therefore it will never find what the user passes, hence, false is always returned.
Related: Should I mysql_real_escape_string the password entered in the registration form?
Update #1
As spotted by #mario, you seem to have spaces in your query when you are passing the values to it as such, it is searching your table for incorrect values.
Reading Material
Prepared Statements

PHP Secure login systems utilizing password encryption scheme

I've been developing a secure login page for users but somehow the password verification seems not to work when logging in.
The code below seems to locate the username in the database I've created in MySql, but mainly the password doesn't match every time.
I've made all possible changes, tried all advices but still, no success. If anyone has any solutions for this issue it would be greatly appreciated.
Error always displays that the password is not the right one.
Login Page:
<?php
/* User login process, checks if user exists and password is correct */
// Escape email to protect against SQL injections
$username = $mysqli->escape_string($_POST['username']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$result = $mysqli->query("SELECT * FROM `users` WHERE `username`='$username'");
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that username doesn't exist!";
header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
if ( password_verify($_POST['password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['username'] = $user['username'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: dashboard.html");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error.php");
}
}
Registration Page:
<?php
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
// Set session variables to be used on profile.php page
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli->escape_string($_POST['lastname']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'") or die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO users (first_name, last_name, email, password, hash, active) "
. "VALUES ('$first_name','$last_name','$email','$password', '$hash', 1)";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['active'] = 0; //0 until user activates their account with verify.php
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"Confirmation link has been sent to $email, please verify
your account by clicking on the link in the message!";
header("location: profile.html");
}
else {
$_SESSION['message'] = 'Registration failed!';
header("location: error.php");
}
}
Here's the login/signup form the user utilizes to sign in into the system: "http://riselamagana.byethost4.com/projects/webdev3/production/index.php"
and the database would be:
table "users"
The password hash that was generated for "password_28" was: " $2y$10$W3bOAG0BP/DExr/qpiT0ueVS3YHb2NVeSC3.oMAaVQbHlodJVudK.".
It still gives me the error that the password isn't correct, my guess is that the password when compared don't match, but I'm not sure why.
Any further suggestions would surely be appreciated.
The password hash that was generated for "password_28" was: " $2y$10$W3bOAG0BP/DExr/qpiT0ueVS3YHb2NVeSC3.oMAaVQbHlodJVudK.".
Story checks out.
It still gives me the error that the password isn't correct, my guess is that the password when compared don't match, but I'm not sure why.
// ...
$user = $result->fetch_assoc();
// ...
if ( password_verify($_POST['password'], $user['password']) ) {
// ...
Are multiple rows being returned for $result? Is it possible that you're comparing the wrong hash in this location?
To troubleshoot this, hard-code $_POST['password'] to be "password_28" and see if it still fails. Then revert your change and hard-code your password hash. Does it still fail?
If it fails the first time, you're probably altering $_POST somewhere else in your application and that's causing the validation to fail.
If it fails the second time, first check that you're only getting one row back (otherwise, this is a trivial fix: make sure you use the correct password hahs for the correct user). If you are, you're probably running into an encoding issue with how your password hashes are being stored. Is the database column too short for the password hash? (Generally you want varchar(255) or TEXT for MySQL, since MySQL truncates by default unless you're running in strict mode.)
Finally, I'd like to recommend not using $mysqli->escape_string() and instead adopting prepared statements. Prepared statements are a much more robust strategy for preventing SQL injection in PHP software than escaping.
You're not comparing to the hashed password, you're comparing the raw post password...
//In your code, line 6, you hash the password
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
//On line 16 you don't
if ( password_verify($_POST['password'], $user['password']) ) {
//So try this instead...
if ( password_verify($password, $user['password']) ) {

undefined index on $_SESSION and all $_POST part

I want to make register form for my website. But I faced error and this is my code:
<?php
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
// Set session variables to be used on profile.php page
$_SESSION['email'] = $_POST['email'];
$_SESSION['first_name'] = $_POST['firstname'];
$_SESSION['last_name'] = $_POST['lastname'];
$mysqli = mysqli_connect("localhost","root","","data");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli->escape_string($_POST['lastname']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'],
PASSWORD_BCRYPT));
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM login WHERE email='$email'") or
die($mysqli->error());
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
// active is 0 by DEFAULT (no need to include it here)
$sql = "INSERT INTO login (first_name, last_name, email, password, hash)"
."VALUES ('$first_name','$last_name','$email','$password', '
$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['active'] = 0; //0 until user activates their account with
verify.php
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"Confirmation link has been sent to $email, please verify
your account by clicking on the link in the message!";
// Send registration confirmation link (verify.php)
$to = $email;
$subject = 'Account Verification ( clevertechie.com )';
$message_body = '
Hello '.$first_name.',
Thank you for signing up!
Please click this link to activate your account:
http://localhost/login-system/verify.php?email='.$email.'&
hash='.$hash;
mail( $to, $subject, $message_body );
header("location: profile.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
header("location: error.php");
exit();
}
}
The error state that:
Undefined index: firstname, lastname, email, password
at line set session variables and line for escape all $_POST variables to protect SQL injection. Anyone know how to fix this error. Thank you.
You are missing session_start() at the start of your code, this needs to be called before you echo/output anything to the browser.
You'll also need to add session_start to your error.php to read from the session there.
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers...
The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.
See: http://php.net/manual/en/function.session-start.php
If(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])){
// Escape all $_POST variables to protect against SQL injections
$first_name = $mysqli->escape_string($_POST['firstname']);
$last_name = $mysqli- >escape_string($_POST['lastname']);
}
In PHP, a variable or array element which has never been set is different from one whose value is null; attempting to access such an unset value is a runtime error.
That's what you're running into: the array $_POST does not have any element at the index "username", so the interpreter aborts your program before it ever gets to the nullity test.

When I register it says the login message but the data isn't going to the database

I took a look at this posted question: I am getting no errors but the data is not going into the database on wamp but I did use mysqli for my code.
Here is my code:
<?php
include( "includes/header.php" );
error_reporting(E_ALL); ini_set('display_errors', '1');
$register = $_POST['register'];
//declaring variables needed for the registration form to prevent errors
$fname = "";
$lname = "";
$uname = "";
$email = "";
$email2 = "";
$password = "";
$password2 = "";
$signup_date = "";
$username_check = ""; // check if username exists
//assigning variables from the registration form
$fname = strip_tags($_POST['fname']);
$lname = strip_tags($_POST['lname']);
$uname = strip_tags($_POST['uname']);
$email = strip_tags($_POST['email']);
$email2 = strip_tags($_POST['email2']);
$password = strip_tags($_POST['password']);
$password2 = strip_tags($_POST['password2']);
$signup_date = date("Y-m-d");
if ($register) {
if ($email == $email2) {
$username_check = mysqli_query("SELECT username FROM users WHERE username = '$uname'");
$row = mysqli_num_rows($username_check);
if ($row == 0) {
if ($fname&&$lname&&$uname&&$email&&$email2&&$password&&$password2) {
if ($password == $password2) {
if (strlen($uname)>25||strlen($fname)>25||strlen($lname)>25) {
echo "The maximum limit for username/first name/ last name is 25 characters!";
} elseif (strlen($password)>30||strlen($password)<5) {
echo "Your password must be between 5 and 30 characters long!";
} else {
$password = password_hash($password);
$password2 = password_hash($password2);
$query = mysqli_query('INSERT INTO users VALUES ("","$uname","$fname","$lname","$email","$password","$signup_date","0")');
die("<h2>Welcome to HackerBits</h2>Login to your account to get started . . . ");
}
} else {
echo "Your passwords don't match!";
}
} else {
echo "Please fill in all of the fields.";
}
} else {
echo "Username already taken . . . ";
}
} else {
echo "Your emails don't match!";
}
}
?>
I know it is messy, I am new to php, only 1 week in. So like I said it goes to the die("<h2>Welcome to HackerBits</h2>Login to your account to get started . . . "); part of the code with no errors. Then when I go to my database the user is not in the table. Which means I can then go back to the registration form and put in the same values.
Sorry if this is a bad question, new to stakeoverflow, just tell me and I will fix it up :) I can also give you more info if needed. I am using MAMP by the way.
I connect to the database with the included script:
<?php
$db = new mysqli('mysql:host=localhost;dbname=users_table', 'root', 'taken-out');
?>
Errors given:
Warning: mysqli_query() expects at least 2 parameters, 1 given in /Users/darceymckelvey/Desktop/php/social_network/index.php on line 27
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /Users/darceymckelvey/Desktop/php/social_network/index.php on line 28
Warning: password_hash() expects at least 2 parameters, 1 given in /Users/darceymckelvey/Desktop/php/social_network/index.php on line 37
Warning: password_hash() expects at least 2 parameters, 1 given in /Users/darceymckelvey/Desktop/php/social_network/index.php on line 38
Warning: mysqli_query() expects at least 2 parameters, 1 given in /Users/darceymckelvey/Desktop/php/social_network/index.php on line 39
They are all warnings which I don't think are fatal because it still executes the code to display the login message.
I have tried these lines:
$username_check = mysqli_query($db, "SELECT username FROM users WHERE username = '$uname'");
but same warnings.
Look at what you're using here:
$db = new mysqli('mysql:host=localhost;dbname=users_table', 'root', 'taken-out');
That isn't the syntax to connect with here using the MySQLi_ API, that is PDO syntax.
http://php.net/manual/en/pdo.connections.php
Those are two different animals altogether.
Read the manual
http://php.net/manual/en/mysqli.query.php
Example taken from it:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
So, replace $mysqli with the variable you're using in your query, and pass the db connection to that mysqli_query() function, as I said from the get go.
This besides all the other comments I left in your question and won't retype nor paste, so go over them all again.
Plus, make sure all your POST arrays contain values. Your HTML form is unknown.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Yet, do read the following Q&A on Stack in regards to what I said about password manipulation:
Cleansing User Passwords
And this one in Code review:
Login with password_hash()
The connection parameter is required for mysqli_query:
mysqli_query($db, "SELECT username FROM users WHERE username = '$uname'");
Your DB connection is for PDO:
$db = new mysqli('mysql:host=localhost;dbname=users_table', 'root', 'taken-out');
You need to use mysqli_connect():
$db = new mysqli("localhost", "root", "taken-out", "users_table");
Also, you need to prevent SQL Injection using mysqli_real_escape_string():
$fname = mysqli_real_escape_string($db, $_POST['fname']);
$lname = mysqli_real_escape_string($db, $_POST['lname']);
$uname = mysqli_real_escape_string($db, $_POST['uname']);
Well, mysqli needs to receive the connection handler as first parameter for query:
mysqli_query($db, "SELECT username FROM users WHERE username = '$uname'");
And the password_hash needs a second parameter with the algoritm:
password_hash($password2, PASSWORD_DEFAULT); // Use default algoritm
I recommend to use prepared statements in your queries, it's have more security.

Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

Failed to run query: SQLSTATE[42000]: Syntax error or access
violation: 1064 You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'telephone = '952 123 123' mobiletelephone = '655 000 000' '
at line 4
Can anyone help ?
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// This if statement checks to determine whether the edit form has been submitted
// If it has, then the account updating code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Make sure the user entered a valid E-Mail address
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// If the user is changing their E-Mail address, we need to make sure that
// the new value does not conflict with a value that is already in the system.
// If the user is not changing their E-Mail address this check is not needed.
if($_POST['email'] != $_SESSION['user']['email'])
{
// Define our SQL query
$query = "
SELECT
1
FROM users
WHERE
email = :email AND
telephone = :telephone AND
mobiletelephone = :mobiletelephone
";
// Define our query parameter values
$query_params = array(
':email' => $_POST['email']
);
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Retrieve results (if any)
$row = $stmt->fetch();
if($row)
{
die("This E-Mail address is already in use");
}
}
// If the user entered a new password, we need to hash it and generate a fresh salt
// for good measure.
if(!empty($_POST['password']))
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
}
else
{
// If the user did not enter a new password we will not update their old one.
$password = null;
$salt = null;
}
// Initial query parameter values
$query_params = array(
':email' => $_POST['email'],
':telephone' => $_POST['telephone'],
':mobiletelephone' => $_POST['mobiletelephone'],
':user_id' => $_SESSION['user']['id'],
);
// If the user is changing their password, then we need parameter values
// for the new password hash and salt too.
if($password !== null)
{
$query_params[':password'] = $password;
$query_params[':salt'] = $salt;
}
// Note how this is only first half of the necessary update query. We will dynamically
// construct the rest of it depending on whether or not the user is changing
// their password.
$query = "
UPDATE users
SET
email = :email,
telephone = :telephone,
mobiletelephone = :mobiletelephone
";
// If the user is changing their password, then we extend the SQL query
// to include the password and salt columns and parameter tokens too.
if($password !== null)
{
$query .= "
, password = :password
, salt = :salt
";
}
// Finally we finish the update query by specifying that we only wish
// to update the one record with for the current user.
$query .= "
WHERE
id = :user_id
";
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Now that the user's E-Mail address has changed, the data stored in the $_SESSION
// array is stale; we need to update it so that it is accurate.
$_SESSION['user']['email'] = $_POST['email'];
$_SESSION['user']['telephone'] = $_POST['telephone'];
$_SESSION['user']['mobiletelephone'] = $_POST['mobiletelephone'];
// This redirects the user back to the members-only page after they register
header("Location: members.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to members.php");
}
?>
As stated by the error message, you have a syntax error in your SQL query:
SELECT
1
FROM users
WHERE
email = :email
telephone = :telephone
mobiletelephone = :mobiletelephone
You need to combine your WHERE clauses with some logical operator. For example, if all three of these clauses must be true in the query then you would use the AND operator:
SELECT
1
FROM users
WHERE
email = :email AND
telephone = :telephone AND
mobiletelephone = :mobiletelephone
Similarly, your UPDATE query needs to separate fields being updated with a comma:
UPDATE users
SET
email = :email,
telephone = :telephone,
mobiletelephone = :mobiletelephone
(Note: Following that query, it looks like you then append more fields to the SET clause. You'll want to make sure by the time the whole query is constructed that each one is separated by a comma.)

Categories