I have a variable $success set to $success = "Successfully Created" but the var $success has no value inside HTML.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
if (isset($_POST['okbutton'])) {
if (isset($_POST['clientuser'], $_POST['clientpass'])) {
$clientuser = $_POST['clientuser'];
$clientpass = $_POST['clientpass'];
$_SESSION['cuser'] = $clientuser;
$_SESSION['cpass'] = $clientpass;
header('Location: trialaccount.php');
die();
}
}
}
try {
if (isset($_SESSION['cuser'])) {
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
if ($checkdup == 0) {
$stmt = $conn->prepare("INSERT INTO user (user_id, user_pass, user_online, user_enable, user_start_date, user_end_date, reseller, type) VALUES (:clientuser, :clientpass,0, 1, now(), now() + interval 4 hour, :panelUSER, 'Trial')");
$stmt->bindParam(':clientuser', $_SESSION['cuser']);
$stmt->bindParam(':clientpass', $_SESSION['cpass']);
$stmt->bindParam(':panelUSER', $username);
$stmt->execute();
$success = "Trial Account Created Successfully!";
} else {
$error = "Username '" . $_SESSION['cuser'] . "' is already taken. Try to input unique username." ;
}
}
} catch (PDOException $e) {
echo "Error: Database Error";
}
Inside my HTML, I use echo!
<?php if(isset($success)){ echo $success; } ?>
var $success is returning the value on my personal smartphone,
but no value on other devices.
I dont know what is happening?
Can I use Session instead? ty
Your method does not get the total row count. Therefore, it doesn't go through (if($checkdup == 0)) to set the value for $success. You can try the code below.
Replace:
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
With:
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->fetchColumn();
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.
This is my Code:
public function enUser($userID) {
try {
$userStatus = "Y";
$tokenCode = "";
$sql = ('UPDATE tbl_users SET userStatus = ? AND tokenCode = ? WHERE userID = ?');
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $userStatus);
$stmt->bindParam(2, $tokenCode);
$stmt->bindParam(3, $userID);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
This is my enum in database
I have try more to edit it. But in database always appear nothing. I mean in the field 'userStatus' after running the update script, its just value like "" (empty). Can any one help me? Thanks.
You update must be:
'UPDATE tbl_users SET userStatus = ?, tokenCode = ? WHERE userID = ?
See the comma instead of AND
And make sure that $userID exists in your DB
SQL table consist of Id(AI),PID,AID,WEB,ADVERT
My code gets all variables but does not registers anything. But There are two methods of registration.
A. Form includes only to fill PID and Website, where ADVERT is sent hidden.
B. Form includes PID,AID,and website where Advert is sent hidden.
PID is not unique and can be multiple
AID is Unique or 0 if not registered selecting the FORM A in which AID is passed as 0 or NULL
Website is not unique and can be duplicate
If AID is null or 0
IF AID is NULL Check if PID and WEB match [Only Once registered if AID is null]
IF AID is Not NULL Check if AID,PID and WEB is already registered. [Already exist]
LASTLY If Everything is OKAY Register the product in database.
<?php
session_start();
$u = $_SESSION['username']; //GETS Session username to register a product
require('db.php'); //db connection
// ----------------PART A------------
//This gets the ID index Number of user from Member Table
$user = "SELECT id from members WHERE username=?";
$stmt = $ref->prepare($user);
$stmt->bind_param("s", $u);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed at 1: ' . htmlspecialchars($stmt->error));
}
$stmt->bind_result($ux);
$stmt->fetch();
$stmt->close();
echo "Pass A <br>"; //Testing purpose
// ----------------------------------------------------------
$aid = $_POST['proslot'];
$web = $_POST['web'];
$pid = $_POST['pub'];
$advert = $_POST['advert'];
//-------------INFO DEBUG-----------------
//Testing Codes Variables pass
echo "<br>uid:<br>".$ux; // User ID
echo "<br>advert:<br>".$advert; //Product advertiser
echo "<br>pid:<br>".$pid; //Product id
echo "<br>aid:<br>".$aid; //audit id
echo "<br>web:<br>".$web; //Product website
//------------------------------------------------------
//-------------------PART B-----------------------------
if($_POST['adslot'] != NULL){
//Cheack if AID and WEBSITE matches any existing record.
$valid = "SELECT id from prologger WHERE aid=? AND userweb=?";
$stmt = $ref->prepare($valid);
$stmt->bind_param("is", $aid,$web);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed at 2: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
$val = $stmt->num_rows;
if($val > 0){
echo "Product Already exist :";
$stmt->close();
$ref->close();
exit();
} else{
$stmt->close();
$ref->close();
}
echo "Pass B[1]";
//---------------------PART B[2]-------------------------
} else {
//Cheack if PID,AID and WEBSITE matches any existing record.
$valid = "SELECT id from prologger WHERE pid=? AND aid=? AND userweb=?";
$stmt = $ref->prepare($valid);
$stmt->bind_param("sis", $pid, $aid,$web);
if($_POST['adslot'] == '0' || $_POST['adslot'] == NULL) {
$aid = '0' or $aid = NULL;
} else {
$aid = $_POST['proslot'];
}
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed at 3: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
$val2 = $stmt->num_rows;
if($val2 > 0){
echo "Unique product per website Required. This product is already registered to this website:"
$stmt->close();
$ref->close();
exit();
}
$stmt->close();
//------------------------------------------------------
//------------------------PART C------------------------
echo "Pass C";
echo "<br>ROW 1:<br>".$val; //DEBUG VALUE
$sql = "INSERT INTO prologger (uid,advert,pid,aid,userweb) VALUES (?,?,?,?,?)";
$stmt = $ref->prepare($sql) ;
$stmt->bind_param("sssis", $ux , $advert, $pid, $aid , $web); //bind variables
if($_POST['adslot'] == NULL) {
$aid = '0';
} else {
$aid = $_POST['adslot'];
}
$input = $_POST['web'];
$input = trim($input, '/');
// If not have http:// or https:// then prepend it
if (!preg_match('#^http(s)?://#', $input)) {
$input = 'http://' . $input;
}
$urlParts = parse_url($input);
// Remove www.
$web = preg_replace('/^www\./', '', $urlParts['host']);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: at 4 ' . htmlspecialchars($stmt->error));
}
$stmt->close();
$ref->close();
echo "Pass Final";
}
//------------------------------------------------------
?>
I fixed it myself. There was an "IF else" Condition that was in this above code Part B
if($_POST['adslot'] != NULL){ //code } else { rest of the code }
where Else needed to be removed
and a $ref->close in the Part B in the else statement of if($val>0) condition which needed to be removed to fix the issue.
I'm having a problem with the following PHP script. Specifically, the part that creates the user_id. This is part of a larger registration.php file that works fine without the section that creates the user_id.
As you can see, it's a while loop that uses a variable, $useridexits, to control the loop. It's set to true by default, so the loop runs. A random number is generated and then checked against the database. If a result is returned, the $useridexists variable is set to true and the loop continues. If no results are returned, $useridexists is set to false, so the loops stops. The number generated is then set to $userid and is then added to the database in the following section.
Here's the code:
//This section creates a new userid for each user.
//This varible is used by the while loop and is set to true by default.
$useridexists = true;
//While loop to create userid and check the database to see if the userid
//already exists. If it does, the while loop keeps going until a unique
//user id is created.
while($useridexists){
// Function to create random user id number.
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(':number' => '$number');
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
}
$userid = $number;
// This section adds the values to the database:
$query = "INSERT INTO users (username, password, email, firstname, lastname, user_id) VALUES ( :user, :pass, :email, :firstname, :lastname, :uid)";
//update tokens with the actual data:
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password'],
':email' => $_POST['email'],
':firstname' => $_POST['firstName'],
':lastname' => $_POST['lastName'],
':uid' => $userid
);
//run the query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added! Please log in.";
echo json_encode($response);
$email= mysql_escape_string($_POST['email']);
$username = mysql_escape_string($_POST['username']);
If I comment out this section, everything works:
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(
':number' => '$number'
);
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
If I don't comment that section out, I don't get any errors, but nothing gets added to the database.
Everything works except the part that checks the database to see if the user_id already exists and changes the $useridexists variable to false, which should escape the while loop. When I add that, nothing gets added to the database.
BTW: I'm using a 1 digit value for testing purposes, but I'll change it to $number = randomNumber(7); once the code actually works.