can you help out a beginner trying to learn PHP? I wrote a code for changing password without any validations yet, just to change it and it does not work. It's been days I've been trying and couldn't figure out what's wrong. Thanks in advance.
id is variable name in database where id is kept.
db connection is done with first line and it definitely works.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
print_r($_SESSION);
function changePSW()
{
//$password = $_POST['currPassword']; // required
$newPassword = $_POST['newPassword']; // required
//$newPassword2 = $_POST['NewPassword2']; // required
$newPasswordH = password_hash($newPassword, PASSWORD_DEFAULT);
echo($newPassword);
$id = $_SESSION['userID'];
echo($id);
// create PDO connection object
$dbConn = new DatabaseConnection();
$pdo = $dbConn->getConnection();
try {
$statement = $pdo->prepare("SELECT * FROM `users` WHERE id = :id LIMIT 1");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
echo "SADASDASD";
// no user matching the email
if (empty($result)) {
$_SESSION['error_message'] = 'Couldnt find user';
header('Location: /Online-store/userForm.php');
return;
}
$sql = "UPDATE users SET password=:newPasswordH WHERE id = :id";
// Prepare statement
$stmt = $pdo->prepare($sql);
echo "AFGHANIKO";
// execute the query
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
echo "IHAAA";
echo($update_status);
if ($update_status === TRUE) {
echo("Record updated successfully" . "\r\n");
echo nl2br("\nPassword: ");
echo ($newPassword);
echo nl2br("\nHashed Password: ");
echo ($newPasswordH);
return true;
} else {
echo "Error updating record";
die();
}
} catch (PDOException $e) {
// usually this error is logged in application log and we should return an error message that's meaninful to user
return $e->getMessage();
}
}
if($_SESSION['isLoggedIn'] == true) {
require_once("database/DatabaseConnection.php");
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);
changePSW();
}
?>
$update_status = $stmt->execute(array(':newPasswordH' => $newPasswordH, ':id' => $id));
This is what I needed to have instead of
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
Related
I have three queries on my login script. One select query checks the users' credentials, another to update the last login, and the third one is a select query to see whether the user exists in another table, so if the user exists in the table, go some where. If the user doesn't exist, go somewhere else.
The third query is the one is acting weird. Below:
require_once '../includes/sessions.php';
//echo 'hello';
$employerlogindata = $_POST['employerlogindata'];
$data = json_decode($employerlogindata);
$employeremailfromjs = $data->employeremail;
$employerpasswordfromjs = $data->employerpassword;
//sanitization
$employeremail = htmlentities($employeremailfromjs);
$employerpassword = htmlentities($employerpasswordfromjs);
//PHP validation rules
$validflag = true;
function checkblanks($variable){
if($variable == ''){
$validflag = false;
print_r('Empty Inputs. Please try again.');
}else {
$variable = trim($variable);
$variable = stripslashes($variable);
return $variable;
}
}
checkblanks($employeremail);
checkblanks($employerpassword);
if($validflag == false) {
echo 'You have problematic entries. Try again.';
} else {
try{
$sql = "SELECT EID AS dbeid, EMPLOYER_EMAIL AS dbemail, `PASSWORD` AS dbpwd, EMPLOYER_NAME AS dbcompanyname, LAST_LOGIN AS dblastlogin FROM userpwd WHERE EMPLOYER_EMAIL = :employeremail;";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
//echo "select statement successfully executed";
//echo $sql;
} catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
//echo $query->rowCount();
if ($query->rowCount() == 0){
echo "Email/Password combo was not found in the system.";
}else {
$result = $query->fetch(PDO::FETCH_OBJ);
//print_r($result);
$dbeid = $result->dbeid;
$dbemail = $result->dbemail;
$dbpwd = $result->dbpwd;
$dbcompanyname = $result->dbcompanyname;
$dblastlogin = $result->dblastlogin;
//echo $dbeid;
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid;
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
echo "Email/Password combination is invalid. Please Try Again.";
}
try{
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
$stmt->execute();
}catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$res = $stmt->fetch();
$eid = $res['EID'];
$count = $stmt->rowCount();
if($stmt->rowCount() == 1){
echo "employerdashboard.php $eid $count";
$stmt->closeCursor();
} else if ($stmt->rowCount() == 0){
echo "e_profile.php $eid $count";
$stmt->closeCursor();
}
}
}
?>
After a set of login credential is successful, the script hits both the second and the third queries. However, the third query takes on the results of the previous ran query. After a second click on the frontend with the same credentials, it produces the right results.
I thought maybe I could find the functionality of mysqli_free_result() in PDO's closeCursor, but that doesn't work. I want it to produce the right result the first time.
Any clues as to why this is happening?
Your variable is out of date (or at least that is my theory), as I said in the comments.
If you have
global $sessemployerid = $_SESSION['EID'];
Then you do
$_SESSION['EID'] = $dbeid;
Then you use $sessemployerid it will not be equal to $_SESSION['EID'] = $dbeid. It will be equal to the previous value of the session when it was assigned, which may or may not be correct. Probably on the first attempt it is wrong, then on subsequent attempts it is correct.
Just to lay it out a bit further:
//you assign $sessemployerid way up here
global $sessemployerid = $_SESSION['EID'];
...
//then you update the session
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid; //<--- here you update the session but neglect $sessemployerid
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
....
//then you use $sessemployerid, but it has a stale value (sometimes)
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
To fix this you could use a reference assignment
global $sessemployerid =& $_SESSION['EID'];
This can be demonstrated by this simple code:
$a = 1;
$b =& $a; //initial assignment, with reference
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is auto-magically updated
See it here
Ouputs
1
2
If you do it this way (the "normal" way)
$a = 1;
$b = $a; //initial assignment, normal
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is not updated
The output is
1
1
Alternatively you could simply update the global after changing the session's value:
if(password_verify($employerpassword, $dbpwd)){
...
$_SESSION['LAST_LOGIN'] = $dblastlogin;
global $sessemployerid = $_SESSION['EID'];
}else{
...
Because the value of $sessemployerid is out of sync with $_SESSION['EID'] you will get inconstant behavior depending on if you had updated the session or not on a previous page attempt.
Hope that makes sense.
I'm trying to set a session variable in php using Slim. I want the users id to be stored as a variable to use elsewhere. I think I have the syntax or order wrong in my functions.
Here is my function to set the variable:
function loadAdmin()
{
//Set new session and save user id to variable
if (!isset($_SESSION)) {
session_start();
}
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('token');
$token_exists = getToken_Validate();
if($token_exists) {
$sql = "SELECT id, title AS admin_title, last_name AS admin_last_name
FROM admin WHERE token=:token";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':token', $token);
$stmt->execute();
$admin = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($admin);
$_SESSION['uid'] = $stmt['id'];
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} else {
echo '{"err": "failed"}';
}
}
Here is my function to use the variable when fetching specific data:
function loadDashboard()
{
session_start();
$uid = $_SESSION['uid'];
$token_exists = getToken_Validate();
if ($token_exists) {
//Get number of rows from multiple tables
$sql = "SELECT
(SELECT COUNT(*) FROM users WHERE id=:uid) AS total_students,
(SELECT COUNT(*) FROM subjects) AS total_subjects,
(SELECT COUNT(*) FROM notes) AS total_notes";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':uid', $uid);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} else {
echo '{"err": "failed"}';
}
}
The Slim error I get after trying to loadDashboard is:
Undefined index: uid
Sorry if my PHP is awful, any help is appreciated.
Turns out it had nothing to do with Slim.
$_SESSION['uid'] = $stmt['id']; was not storing anything to the variable.
I had to first bind the id column to a variable:
$stmt->bindColumn('id', $uid);
Then I could set that variable as a session variable:
$_SESSION['uid'] = $uid;
Here is the full working function:
function loadAdmin()
{
if (!isset($_SESSION)) {
session_start();
}
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('token');
$token_exists = getToken_Validate();
if($token_exists) {
$sql = "SELECT
id,
title AS admin_title,
last_name AS admin_last_name
FROM admin WHERE token=:token";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':token', $token);
$stmt->execute();
$stmt->bindColumn('id', $uid);
$admin = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
$_SESSION['uid'] = $uid;
echo json_encode($admin);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
else {
echo '{"err": "failed"}';
}
}
Hello guys I have been trying to delete a file using php and I want it to delete the main post, reply's and like then update to the author -10 in his/her point.
Here is my code, using PDO:
<?php session_start();
if(isset($_POST['id'])){
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("DELETE FROM code WHERE cid= {$id}");
$stmt = $db_conn->prepare("DELETE FROM comment WHERE id = {$id}");
$stmt = $db_conn->prepare("DELETE FROM likes_map WHERE lid = {$id}");
$stmt = $db_conn->prepare("UPDATE users SET point -1 WHERE username = {$u}");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':cid', $id);
$stmt->bindParam(':lid ', $id);
$stmt->bindParam(':u ', $_SESSION['username']);
$stmt->execute();
echo "deleted"
} catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}else{
echo "You are not allow to delete this";
}
?>
Your first problem is that you are preparing more than one query on the same statement handle and therefore loosing the link to that prepared statement when you prepare the next query.
You are also only executing the queries once and not once per statement!
Also your prepared sql statement do not have the parameters set with the correct syntax
It would also be a good idea to run this code inside a transaction, so if any update of the database fails you are not left with just bits of this process comepleted. This assumes the database is an INNODB database and not an MYISAM one, as transactions dont work on MYISAM
<?php
session_start();
if(!isset($_POST['id'])){
echo "You are not allow to delete this";
exit;
}
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// start a transaction
$db_conn->beginTransaction();
$d_code = $db_conn->prepare("DELETE FROM code WHERE cid= :id");
$d_code->bindParam(':id', $id);
$d_comment = $db_conn->prepare("DELETE FROM comment WHERE id = :id");
$d_comment->bindParam(':id', $id);
$d_like = $db_conn->prepare("DELETE FROM likes_map WHERE lid = :id");
$d_like->bindParam(':id ', $id);
$u_user = $db_conn->prepare("UPDATE users SET point -1 WHERE username = :u");
$u_user->bindParam(':u ', $_SESSION['username']);
$d_code->execute();
$d_comment->execute();
$d_like->execute();
$u_user->execute();
$db_conn->commit();
echo "deleted";
} catch(PDOException $e) {
$db_conn->rollBack();
echo "Error:" . $e->getMessage();
}
$db_conn = null;
?>
<?php
if (isset($_GET['key']) && isset($_GET['username'])) {
$activationQuery = "SELECT activationKey FROM users WHERE username = :username";
$activationQueryParams = array(':username' => $_GET['username']);
try {
$stmt = $db->prepare($activationQuery);
$result = $stmt->execute($activationQueryParams);
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$activationRowCount = $stmt->rowCount();
if ($activationRowCount) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$key = $_GET['key'];
$databaseKey = $row['activationKey'];
if ($key == $databaseKey) {
$updateActivated = "UPDATE users SET activated = 1 WHERE username = :username";
$updateActivatedParams = array(':username' => $_GET['username']);
try {
$stmt = $db->prepare($updateActivated);
$result = $stmt->execute($updateActivatedParams);
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$updateKey = "UPDATE users SET activationKey = '' WHERE username = :username";
$updateKeyParams = array(':username' => $_GET['username']);
try {
$stmt = $db->prepare($updateKey);
$result = $stmt->execute($updateKeyParams);
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
echo "Your account has been activated!";
} else {
echo "Sorry, it looks like that activation key doesn't exist!";
}
}
}
}
?>
Right now, this code works as it's suppose to. The problem I'm having is when it passes all checks and gives me back the echo:
Your account has been activated!
When it spit's out that message, it terminates all HTML below it from running. But when the conditions are not met and it spits out the error echo, the HTML is rendered just fine with no issues.
I have looked this over soo many times and can't see anything that I need to change, but, that's why I'm asking here. Hopefully it's something simple I missed.
I am using luracast restler for making REST APIs. I am trying to update user using post method. But my sql is not executed and i dont know how to look for sql errors in json format.
My API code is
<?php
class User
{
public $dp;
function __construct()
{
$this->dp = new DB_PDO_MySQL();
}
function post($request_data = NULL)
{
$response = array();
if(array_key_exists('user_id', $request_data)){
$response = $this->dp->updateUser($request_data);
}else{
$response = $this->dp->signUp($request_data);
}
return $response;
}
}
and updateUser function in MySQL is as
function updateUser($postData){
$response = "";
$data = array();
if($this->checkToken($postData['token'])){
$sql = $this->db->prepare('SELECT * FROM phpclassifieds_acc_users WHERE username = :username');
$sql->execute(array(':username' => $postData['username']));
if($sql->rowCount()>0)
{
return $this->response(0,'','The Username ('.$postData[username].') is already in use');
}
$sql = $this->db->prepare('SELECT * FROM phpclassifieds_acc_users WHERE email = :email');
$sql->execute(array(':email' => $postData['email']));
if($sql->rowCount()>0)
{
return $this->response(0,'','The Email Address ('.$postData[email].') is already in use');
}
$sql = "UPDATE phpclassifieds_acc_users SET
type = :type,
username = :username,
password = :password,
name = :name,
address =:address,
address2 =:address2,
address_city = :address_city,
city =:city,
zipcode =:zipcode,
state =:state,
email =:email,
newsletter =:newsletter
WHERE user_id = :user_id";
try{
$stmt =$this->db->prepare($sql);
$stmt->bindParam(':type',$postData['type'],PDO::PARAM_STR);
$stmt->bindParam(':username',$postData['username'],PDO::PARAM_STR);
$stmt->bindParam(':password',$postData['password'],PDO::PARAM_STR);
$stmt->bindParam(':name',$postData['name'],PDO::PARAM_STR);
$stmt->bindParam(':address',$postData['address'],PDO::PARAM_STR);
$stmt->bindParam(':address2',$postData['address2'],PDO::PARAM_STR);
$stmt->bindParam(':address_city',$postData['address_city'],PDO::PARAM_STR);
$stmt->bindParam(':city',$postData['city'],PDO::PARAM_STR);
$stmt->bindParam(':zipcode',$postData['zipcode'],PDO::PARAM_STR);
$stmt->bindParam(':state',$postData['state'],PDO::PARAM_STR);
$stmt->bindParam(':email',$postData['email'],PDO::PARAM_STR);
$stmt->bindParam(':user_id',$postData['user_id'],PDO::PARAM_INT);
$var = $stmt->execute();
}
catch(PDOException $e) {
$err[] = var_dump($e->getMessage());
echo json_encode($err);
}
if($var){
$response = "Update Successfully done..";
$sqlSelect = $this->db->prepare('SELECT * FROM phpclassifieds_acc_users WHERE user_id = :user_id');
$sqlSelect->execute(array(':user_id'=>$postData['user_id']));
$data = $this->id2int($sqlSelect->fetch());
}else{
$response = "Update is unsuccessful ..";
}
return $this->response(1,$data,$response);
}
}
The problem is when i dont use try catch the output is "Update unsucessful...." and when i use try catch i get "Unexpected token s".
This line of code is strange
$err[] = var_dump($e->getMessage());
echo json_encode($err);
It's weird to encode a var_dump into json, you should just be able to do:
$err[] = $e->getMessage();
echo json_encode($err);
or you can get the error from errorInfo()
echo json_encode($this->db->errorInfo());
Don't forget to bind the newsletter parameter:
$stmt->bindParam(':newsletter',$postData['newsletter'],PDO::PARAM_STR);