<?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.
Related
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));
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.
In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders
What i'm trying to do is make a function that gets a user permission level as seen here.
function userPermission($level, $conn){
try{
$sql = "SELECT * FROM `users` WHERE username = :Player AND level = :Level ";
$s = $conn->prepare($sql);
$s->bindValue(":Player", $_SESSION['username']);
$s->bindValue(":Level", $level);
$s->execute();
return true;
} catch(PDOException $e) {
error_log("PDOException: " . $e->getMessage());
return false;
}
}
and once I go to the page and input the code that should in-tile the functionality of this function. It doesn't work at all.
Here is the code that I inputted
<?php if (!userPermission('0', $conn) == 2) {
echo '<input type="radio" id="tab-7" name="tab-group-1">
<label for="tab-7">Permissions</label>';
} else {
echo '<input disabled=disabled type="radio" id="tab-7" name="tab-group-1">
<label id="disabled" for="tab-7">Permissions</label>';
}
?>
The 0 is the current level of the user and I was using that as a test, as for the == 3 that's what the rank has to be in order to access the tab
Anyways, I'm either doing this wrong or I don't know what i'm doing. I get no errors at all but the code I inputted seems unreliable.
Your code just execute but does not return the query result.
I modified your code a little bit as an example
function userPermission($username,$level, $conn){
try{
$sql = "SELECT `user_permission`
FROM `users`
WHERE username = :username AND level = :Level ";
$s = $conn->prepare($sql);
$s->bindValue(":username", $username);
$s->bindValue(":level", $level);
$s->execute();
$row = $s->fetch();
return $row['user_permission'];
} catch(PDOException $e) {
error_log("PDOException: " . $e->getMessage());
return -1;
}
}
Make sure the session is set also
session_start();
$usermame = $_SESSION['username'];
if (!userPermission($username,'0', $conn) == 2) {...
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);