usercake updating field isn't working - php

I use User Cake for user management system but I am struggling with one problem, I have had asked this question in their website but I couldn't find anyone to help me out.
What I need is simply making the users be able to update their information. ex. first name, phone, email....The email field updates correctly as it came with that functionality.
The fields that I added aren't being updated. Can someone give me some hints on what I am missing?
Here is what I tried looking at the email field. I have First Name field.
Funcs.php
//Update a user's email
function updateEmail($id, $email)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
email = ?
WHERE
id = ?");
$stmt->bind_param("si", $email, $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
//Update a user's first name. This is what isn't working.
function updateFirstname($id, $firstname)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
firstname = ?
WHERE
id = ?");
$stmt->bind_param("si", $firstname, $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
Here is class.user.php
class loggedInUser {
public $email = NULL;
public $hash_pw = NULL;
public $user_id = NULL;
public $firstname = NULL;
//Update a users email
public function updateEmail($email)
{
global $mysqli,$db_table_prefix;
$this->email = $email;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
email = ?
WHERE
id = ?");
$stmt->bind_param("si", $email, $this->user_id);
$stmt->execute();
$stmt->close();
}
//Update a users first name
public function updateFirstname($firstname)
{
global $mysqli,$db_table_prefix;
$this->firstname = $firstname;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
firstname = ?
WHERE
id = ?");
$stmt->bind_param("si", $firstname, $this->user_id);
$stmt->execute();
$stmt->close();
}
}
user_settings.php where I can change the fields and hit the update button. If I change the email and hit update, the email is updated but when I change firstname and hit update I get
nothing to update
//Prevent the user visiting the logged in page if he is not logged in
if(!isUserLoggedIn()) { header("Location: login.php"); die(); }
if(!empty($_POST))
{
$errors = array();
$successes = array();
$password = $_POST["password"];
$password_new = $_POST["passwordc"];
$password_confirm = $_POST["passwordcheck"];
$errors = array();
$email = $_POST["email"];
$firstname = $_POST["firstname"];
//Perform some validation
//Feel free to edit / change as required
//Confirm the hashes match before updating a users password
$entered_pass = generateHash($password,$loggedInUser->hash_pw);
if (trim($password) == ""){
$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
}
else if($entered_pass != $loggedInUser->hash_pw)
{
//No match
$errors[] = lang("ACCOUNT_PASSWORD_INVALID");
}
if($email != $loggedInUser->email)
{
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
else if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
else if(emailExists($email))
{
$errors[] = lang("ACCOUNT_EMAIL_IN_USE", array($email));
}
//End data validation
if(count($errors) == 0)
{
$loggedInUser->updateEmail($email);
$loggedInUser->updateFirstname($firstname);
$successes[] = lang("ACCOUNT_EMAIL_UPDATED");
}
}
if ($password_new != "" OR $password_confirm != "")
{
if(trim($password_new) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_NEW_PASSWORD");
}
else if(trim($password_confirm) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_CONFIRM_PASSWORD");
}
else if(minMaxRange(8,50,$password_new))
{
$errors[] = lang("ACCOUNT_NEW_PASSWORD_LENGTH",array(8,50));
}
else if($password_new != $password_confirm)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
//End data validation
if(count($errors) == 0)
{
//Also prevent updating if someone attempts to update with the same password
$entered_pass_new = generateHash($password_new,$loggedInUser->hash_pw);
if($entered_pass_new == $loggedInUser->hash_pw)
{
//Don't update, this fool is trying to update with the same password ¬¬
$errors[] = lang("ACCOUNT_PASSWORD_NOTHING_TO_UPDATE");
}
else
{
//This function will create the new hash and update the hash_pw property.
$loggedInUser->updatePassword($password_new);
$successes[] = lang("ACCOUNT_PASSWORD_UPDATED");
}
}
}
if(count($errors) == 0 AND count($successes) == 0){
$errors[] = lang("NOTHING_TO_UPDATE");
}
}

if($email != $loggedInUser->email)
{
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
else if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
else if(emailExists($email))
{
$errors[] = lang("ACCOUNT_EMAIL_IN_USE", array($email));
}
//End data validation
if(count($errors) == 0)
{
$loggedInUser->updateEmail($email);
$successes[] = lang("ACCOUNT_EMAIL_UPDATED");
}
}
Clone this function as
if($firstname != $loggedInUser->firstname) blah blah
Remove this line from the function above move it in the new function:
loggedInUser->updateFirstname($firstname);
Just clone the function,just as you have done above.Change the error messages and add function to validate the name,it will be somewhat different,it will require more work.

Related

Internal Sever error when trying to update query in PHP

Am actually building a login and register system but having these internal error in the email activation part, when am trying to change the active table to 1, if users email and email_code matches.
the activate.php code :
<?php
} else if (isset($_GET['email'], $_GET['activation']) === true) {
$email = trim($_GET['email']);
$email_code = trim($_GET['activation']);
if (email_exists($email) == false) {
$errors[] = 'Ooops, We counldn\'t find that email address';
} else if (activate($email, $email_code) == false) {
$errors[] = 'Ooops, We had problem activating your account';
}
if (empty($errors) == false){
echo output_errors($errors) . '<br><br>';
} else {
header('Location : activate.php?success');
exit();
}
} else {
header('Location: index.php');
exit();
}
?>
The activate($email, $email_code) function :
function activate($email, $email_code) {
global $connection;
$email = $email;
$email_code = $email_code;
$active = 0;
$new_update_active = 1;
$stmt = $connection -> prepare('SELECT id FROM users WHERE email = ? AND email_code = ? AND active = ?');
$stmt -> bind_param('ssi', $email, $email_code, $active);
$stmt -> execute();
$stmt -> store_result();
$stmt -> fetch();
if ($stmt -> num_rows() == 1) {
$update_active = $connection -> prepare('UPDATE users SET active = ? WHERE email = ?');
$update_active -> bind_param('is', $new_update_active, $email);
return true;
} else {
return false;
}
}
The error:
The error image!!
The code is seems correct and am only having these intenal serval when it comes to the part that the email and email_code matches and to change the active table to 1 in the database.
I later spot the error and i just change the
header('Location : activate.php?success');
to
header('Location: activate.php?success');

PHP PDO statement that checks for existing username

currently working on an application and curious as to why my script is going to a blank page once I submit my form. It started occurring when I added a piece to my script that is supposed to go into my database that checks if a username exists and then echos a message if that is the case and echos a message if it isn't the case.
This is the code:
function validateUser() {
global $user, $userErr, $validForm;
$userErr = "";
if ($user == "") {
$userErr = "nothing entered";
$validForm = false;
}
else if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-
Z]*)*$/",$user)) {
$userErr = "invalid characters";
$validForm = false;
}
elseif (strlen($user) > 1) {
$stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
username = :username");
$stmt->bindValue(':username', $user);
$stmt->execute(array($user));
$norows = $result->fetchColumn();
if ($norows > 0 ) {
$userErr = 'Username already taken';
}
else {
$userErr='User added';
}
}
}
The bit that is giving me trouble is the last elseif statement... for some reason it hasn't been doing what it's supposed to do. I've looked at many different sources and I've tried implementing different solutions but nothing has seemed to work. This function runs when the form is submitted just incase you are wondering. Very open to any possible solutions you may have. Because I just can't get it to work... thanks!
Don't Use else if() since you are using different comparison statements. Just replace all your else if() with if() only. Then use $userErr variable to check if the inputs pass all your validations.
function validateUser() {
global $user, $userErr, $validForm;
$userErr = "";
if ($user == "") {
$userErr = "nothing entered";
$validForm = false;
}
if (!preg_match("/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/",$user)) {
$userErr = "invalid characters";
$validForm = false;
}
if (strlen($user) > 1) {
$stmt = $conn->prepare("SELECT COUNT(username) AS num FROM credentials WHERE
username = :username");
$stmt->bindValue(':username', $user);
$stmt->execute(array($user));
$norows = $result->fetchColumn();
if ($norows > 0 ) {
$userErr = 'Username already taken';
}
}
if($userErr == "") {
$userErr='User added';
}
}

PHP check if value exists in Database [duplicate]

This question already has answers here:
How to check if a row exist in the database using PDO?
(3 answers)
Closed 5 years ago.
I am using MySQL and I want to check if the value of the users input $_POST['username'] already exists in my database (in the field username). I have tried this code:
$usernameExists = "SELECT * FROM users WHERE username = " . $_POST['username'];
if ($usernameExists) {
echo "Exists"
}
I put this code after the if (!empty...) statement;
but nothing happened. If you need my full code, it is available here, but I assume the rest of it won't be helpful:
<?php
session_start();
if (isset($_SESSION['user_id'])) { // user is already logged in
header("Location: index.php");
}
require('database.php');
$message = '';
$emailMessage = '';
$usernameMessage = '';
$passwordMessage = '';
$confirmMessage = '';
if (!empty($_POST['email']) && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['confirmPassword'])) { // user submitted form; enter user
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailMessage = 'Invalid email.';
} elseif (strlen($_POST['username']) < 4 || strlen($_POST['username']) > 250) {
$usernameMessage = 'Username has to be between 4 and 250 characters.';
} elseif (!preg_match("/^[a-zA-z0-9]*$/", $_POST['username'])) {
$usernameMessage = 'Username can only contain numbers and letters.';
} elseif (strlen($_POST['password']) < 6 || strlen($_POST['password']) > 250) {
$passwordMessage = 'Password has to be between 6 and 250 characters.';
} elseif ($_POST['confirmPassword'] !== $_POST['password']) {
$confirmMessage = 'Passwords don\'t match THONK';
} else {
$sql = "INSERT INTO users (email, username, password) VALUES (:email, :username, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':username', $_POST['username']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);
if ($stmt->execute()) {
$message = 'Successfully created new user: ' . $_POST['username'];
} else {
$message = 'There was an error lol';
}
}
}
?>
Query the database using a prepared statement. Like this:
$usernameExists = 0;
$sql = 'SELECT username FROM users WHERE username = :username';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username',$_POST['username']);
$stmt->execute();
if($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// row(s) returned
$usernameExists = 1;
} else {
// no row returned
$usernameExists = 0;
}
$stmt->closeCursor();
Then you can do this:
if ($usernameExists) {
echo "Exists"
}

PHP Returning value from If/Else If statement called via class

I am trying to figure out why this isn't working. What I am trying to do is return a value after the function is called. It is a login function which is supposed to check the database for the users status. That value being $userStatus. Depending on the status I'd like to return a value which would then trigger the error. However the script only fires off the first else if statement.
Here is the index page which calls the script
if(isset($_POST['btn-login'])) {
$uname = strip_tags($_POST['txt_uname_email']);
$umail = strip_tags($_POST['txt_uname_email']);
$upass = strip_tags($_POST['txt_password']);
if ($login->doLogin($uname,$umail,$upass)) {
$login->userLoginTime($uname);
$login->redirect('home.php');
} else if ($userStatus == 0) {
$error = "Your account is not active!";
} else if ($userStatus == "") {
$error = "You don't have an account, please sign up";
}
}
?>
Here is the class page where the function is housed.
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT
user_id, user_name, user_email, user_pass, Enabled
FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$userStatus = $userRow['Enabled'];
if ($userStatus == 5) {
if ($stmt->rowCount() == 1) {
if (password_verify($upass, $userRow['user_pass'])) {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
} else {
return false;
}
}
if ($userStatus == 0) {
return $userStatus;
}
if ($userStatus == "") {
return $userStatus;
}
}
$userStatus is never being set. You'll want to set it before your if:
$userStatus = $login->doLogin($uname,$umail,$upass);
if($userStatus === true) {
$login->userLoginTime($uname);
$login->redirect('home.php');
} else if ($userStatus === 0) {
$error = "Your account is not active!";
} else if ($userStatus === "") {
$error = "You don't have an account, please sign up";
}
maybe "txt_uname_email" in
$uname = strip_tags($_POST['txt_uname_email']);
is incorrect? Something with name?

What is wrong with my Register function?

Problem & Explanation
Hello I have just coded a function that first does checking if account exists in database with that name, and then if email exists in database with that entered email.
If not, return true + insert data.
But in this case, nothing happens on submit, it just shows the form, but doesn't inserts the data..
What is wrong with it?
function createAccount($name, $password, $email)
{
global $pdo;
$check_in = $pdo->prepare("SELECT * FROM users WHERE user_name = :username LIMIT 1");
$check_in->execute( array(':username' => $name) );
if (!$check_in->rowCount())
{
$check_in = email_exists($email);
if ($check_in === false)
{
$insert_in = $pdo->prepare
("
INSERT INTO
users
(user_name, user_password, user_email)
VALUES
(:name, :password, :email)
");
$insert_in->execute( array
(
':name' => $name,
':password' => $password,
':email' => $email
));
return true;
}
else
{
return 'exists';
}
}
else
{
return 'user_in_use';
}
}
function email_exists($email)
{
global $pdo;
$check = $pdo->prepare("SELECT * FROM users WHERE user_email = :email LIMIT 1");
$check->execute( array(':email' => $email) );
if ($check->rowCount())
{
return true;
}
else
{
return false;
}
}
This is how I make up the register:
# Creating shortcuts
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
}
# Creating errors array
$errors = array();
if (isset($_POST['submit']))
{
$check_in = createAccount($name, $password, $email);
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
}
}
Question:
What is wrong with this code & how do I fix this? I have no errors at all.
It just won't insert any data to the Database.
Yes, the PDO connection & statements are right, because the login works perfectly.
Thanks a lot!
EDIT!
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
} else {
echo 'Error is there...';
}
It's echoing 'Error is there...' apon submit!
I just want to slap myself!.....
The problem was: The fields were set as INT, therefore we could not store anything but ints...

Categories