PDO PHP UPDATE don´t update Password if not included - php

I have an updating form to update the users information. Here, I have the password input. And I want to, if left blank, not update the password in the database but to leave the one already set up.
For this I have:
$user_password = inputCleaner($_POST['user_password']);
$user_password_repeat = inputCleaner($_POST['user_password_repeat']);
// IF filled, check if both match
if (!empty($user_password) && $user_password != $user_password_repeat) {
$errors .= "Passwords are not the same." . '<br>';
} elseif (!empty($user_password) && $user_password == $user_password_repeat) {
$user_password = hash('sha512', $user_password);
}
// IF NOT FILLED, leave NULL
elseif (empty($user_password)) {
$user_password = '';
}
If all is good, we run the script:
if(!$errors) {
$statement = $connection -> prepare("
UPDATE users SET
user_nickname = :user_nickname,
user_password = COALESCE(NULLIF(:user_password, ''),user_password)
user_pass
user_name = :user_name,
user_last_name = :user_last_name,
user_email = :user_email,
user_picture = :user_picture,
role = :role
WHERE
user_id = :user_id
");
$statement -> execute(array(
':user_nickname' => $user_nickname,
':user_password' => $user_password,
':user_name' => $user_name,
':user_last_name' => $user_last_name,
':user_email' => $user_email,
':user_picture' => $user_picture,
':role' => $role,
':user_id' => $user_id
));
Note my inputCleaner() function is a simple:
function inputCleaner($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
With this, the password is not updated at all, it won´t change it.

Instead of converting '' to NULL and then using COALESCE(), you can simply compare :user_password to ''.
You also had some syntax errors: a missing comma after assigning to user_password and an extra line with user_pass after that.
$statement = $connection -> prepare("
UPDATE users SET
user_nickname = :user_nickname,
user_password = IF(:user_password = '',user_password, :user_password),
user_name = :user_name,
user_last_name = :user_last_name,
user_email = :user_email,
user_picture = :user_picture,
role = :role
WHERE
user_id = :user_id
");```

Related

Inserting data in diferent tables

Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>

Updating password mysqli in PHP if a new one is entered

I'm a little new to PHP and mysqli and don't think I'm going around this the right way; maybe I need to check if it's the same, and if not update the password? I'm not sure how to do this though.
At the moment on the user edit form I'm not passing the current password value, but I can pass it and it will pass as md5 format.
PHP
// user information
$getID = $_POST['id']; // id
$name = $_POST['name']; // name
$username = $_POST['username']; // username
$email = $_POST['email']; // email
$phone = $_POST['phone']; // phone
$password = md5($_POST['password']); // password
if($password == ''){
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?
WHERE id = ?
";
} else {
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?,
password =?
WHERE id = ?
";
}
/* Prepare statement */
$stmt = $mysqli->prepare($query);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
if($password == ''){
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'ssss',
$name,$username,$email,$getID
);
} else {
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'sssss',
$name,$username,$email,$password,$getID
);
}
You did one mistake in your code.do not use MD5 before checking blank password . MD5 also encrypt blank value so $password == '' condition always wrong.
// user information
$getID = $_POST['id']; // id
$name = $_POST['name']; // name
$username = $_POST['username']; // username
$email = $_POST['email']; // email
$phone = $_POST['phone']; // phone
/// do not use md5 here so condition get false always
$password = $_POST['password']; // password
if($password == ''){
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?
WHERE id = ?
";
} else {
// the query
$query = "UPDATE users SET
name = ?,
username = ?,
email = ?,
phone = ?,
password =?
WHERE id = ?
";
}
/* Prepare statement */
$stmt = $mysqli->prepare($query);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
if($password == ''){
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'ssss',
$name,$username,$email,$getID
);
} else {
$password = md5($password);
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param(
'sssss',
$name,$username,$email,$password,$getID
);
}

Login script using PDO

I'm implementing a login script which isn't working correctly. I want users to be able to login with either their usernames or emails. I have two tables:
user - contains login information(username, password, email, isactive)
userprofile - contains profile information
ISSUES/ERRORS:
Logging in with the email addresses doesn't work.
If the username alone is entered, leaving the password field empty, the user is still logged in regardless.
THE CODE(isactive checks if a user's account has been activated after email verification)
$uname = htmlspecialchars($_POST['username']);
$pword = htmlspecialchars($_POST['password']);
$isActive = 1;
$getId = 0;
try{
$stmt = $db->prepare("SELECT * FROM user WHERE username = :username OR email = :email AND password = :password AND isactive = :isactive");
$stmt->execute(array(':username' => $uname, ':email' => $uname, ':password' => $pword, ':isactive' => $isActive));
$numrows = $stmt->fetch(PDO::FETCH_ASSOC);
//to enable me count number of rows returned
$number = $stmt->fetch(PDO::FETCH_NUM);
$_SESSION['username'] = $numrows['username'];
$getId = $numrows['Id'];//get the id of the user
}catch(PDOException $ex){
echo 'QUERY ERROR: ' . $ex->getMessage();
}
/*this checks to see that the user has a profile (userId is a foreign key, thus user.Id = userprofile.userId always)*/
try{
$query = $db->prepare("SELECT * from userprofile WHERE userId = :userId");
$query->execute(array(':userId' => $getId));
$row = $query->fetchAll();
}catch(PDOException $exc){
echo 'QUERY ERROR: ' . $exc->getMessage();
}
//Check results and log user in
if(count($number) == 1 && count($row) == 1){
header("Location: index.php");
}
else {$errorMessage = "<p style='color:#ff851b'>Invalid username or password</p>";}
What do i need to modify to get this working? Thanks
You can easily include the row count in your query as well:
And adjust the query :
SELECT *, count(*) AS numrows
FROM user
WHERE (username = :username OR email = :email) AND
password = :password AND isactive = :isactive
Please make the following changes:
$stmt->execute(array(':username' => $uname,
':email' => $uname,
':password' => $pword,
':isactive' => $isActive));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$row){
throw new Exception('User not found');
}
//get user data
$numrows = (int)$row['numrows'];
if($numrows === 1){
//found a user
$_SESSION['username'] = $row['username'];
$id = $row['Id'];
}
The main issue I see is this one; some brackets are needed:
Before:
$stmt = $db->prepare("SELECT * FROM user WHERE username = :username OR email = :email AND password = :password AND isactive = :isactive");
After:
$stmt = $db->prepare("SELECT * FROM user WHERE ((username = :username AND password = :password) OR (email = :email AND password = :password)) AND isactive = :isactive");
Also, in this line you are assigning $uname to username and email - possible copy/paste error here as well?
$stmt->execute(array(':username' => $uname, ':email' => $uname, ':password' => $pword, ':isactive' => $isActive));
Try
SELECT * FROM user WHERE (username = :username OR email = :email) AND password = :password AND isactive = :isactive"
as query... Should work...

checking username against database pdo

The script works to add user data into the db however I want the check if the username is in use but keep running into this error
Fatal error: Call to a member function rowcount() on a non-object in /home/4507408/public_html/registeruser.php on line 78
I cant seem to manage to do it with PDO, any help would be great!
<?php
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$firstname = $form[ 'firstname' ];
$location = $form[ 'location' ];
$age = $form[ 'age' ];
$email = $form[ 'email' ];
$usercheck = $_POST['username'];
$check = "SELECT username FROM use WHERE username = '$usercheck'";
$query = $DBH->prepare( $check );
$query = $DBH->prepare($check);
$query->execute();
$data = $query->fetchALL();
$check2 = $check->rowcount();
//if the name exists it gives an error
if ($check2 != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
$sql = "INSERT INTO user ( username, password, firstname, location, age, email ) VALUES ( :username, :password, :firstname, :location, :age, :email )";
$query = $DBH->prepare( $sql );
?>
This line:
$check = "SELECT username FROM use WHERE username = '$usercheck'";
is wrong. use is a SQL reserved word. I assume you meant user. It's also a terrible idea to inject a value into the query string with simple variable substitution. The whole point of PDO is to use parametrized queries: http://us1.php.net/pdo.prepared-statements

pdo if statments are not working when checking the value

This is a code that I designed to check if username matches with the email in the database.
If not check the username. if it does not exist, check the email. If it does not exist, create a new username.
The problem is that the query runs and insert a new user every time!! What am I doing wrong??
$word = $_POST['word'];
$explination = $_POST['explination'];
$lhgat = $_POST['lhgat'];
$email = $_POST['email'];
$username = $_POST['username'];
$letterar = idar($_POST['word']);
$letteren = iden($_POST['word']);
if (!empty($word) && !empty($explination) && !empty($lhgat) && !empty($email) && !empty($username) && !empty($letterar) && !empty($letteren)) {
//checking for username and email match
$checkingforuserstmt = $conn->prepare('SELECT id FROM user WHERE username = username AND email = email');
$checkingforuserstmt->execute(array(':username' => $username, ':email' => $email));
$checkingforuserrow = $checkingforuserstmt->fetch(PDO::FETCH_ASSOC);
if($checkingforuserstmt->rowCount() < 0){
//check for username only
$checkingforuserstmt2 = $conn->prepare('SELECT id FROM user WHERE username = username');
$checkingforuserstmt2->execute(array(':username' => $username));
$checkingforuserrow2 = $checkingforuserstmt2->fetch(PDO::FETCH_ASSOC);
if($checkingforuserrow2->rowCount() < 0){
//check for email only
$checkingforuserstmt3 = $conn->prepare('SELECT id FROM user WHERE email = email');
$checkingforuserstmt3->execute(array(':email' => $email));
$checkingforuserrow3 = $checkingforuserstmt3->fetch(PDO::FETCH_ASSOC);
if($checkingforuserrow3->rowCount() < 0){
$insertuser = $conn->prepare("INSERT INTO user VALUES('',:username,:email)");
$insertuser->execute(array(':username' => $username,':email' => $email)); }}}
You need to use the : in the statement, not the binding. for example: select * from table where field = :field not field = field
Otherwise you're just saying the column, not a value.

Categories