PHP check if value exists in Database [duplicate] - php

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"
}

Related

PHP Login Code not working - Database Connection is okay

I'm trying to set up a Register + Login for one of my Sites. The Registration process works completely fine but the Login seems to fail every time.
This is the register.php
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email =?")) {
$error = '';
$query->bind_param('s', $email);
$query->execute();
$query->store_result();
if ($query->num_rows >0) {
$error .= '<p class="error">E-Mail already registered</p>';
}
if (empty($confirm_password)) {
$error .= '<p class="error">Passwords do not match.</p>';
}
if (empty($error)) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your Registration was succesful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
$query->close();
$insertQuery->close();
mysqli_close($db);
}
?>
This is the Login.php
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']) ;
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
if (empty($password)) {
$error .= '<p class="error">Please enter password.</p>';
}
if (empty($error)){
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s',$email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$SESSION["user"] = $row;
header("location: index2.php");
exit;
}else{
$error.= '<p class="error">The password is not valid.</p>';
}
}else{
$error.= '<p class="error">Wrong mail.</p>';
}
}
$query->close();
}
mysqli_close($db);
}
?>
According to Online PHP Checker my Code should be correct. There are no Errors in Console and I really don't know what exactly i did wrong. Hope someone can help me with this!
This line is the issue, I expect:
$row = $query->fetch();
According to the documentation, the fetch() function returns true, false or null - it does not return a row of data. You need to use bind_result() to map the results from the query into variables.
https://www.php.net/manual/en/mysqli-stmt.fetch.php

PHP MSQLI Forgot Password Reset page

I am setting up a PHP lost password page for my website (www.qbstaxsubmission.co.uk) and the code for creating a lost password email which is sent to a user is working just fine. However when the user clicks on the email link he arrives at a new password php page. It's the script on this page which produces a error message 'Registration failure in updating recovery key: INSERT' which fires up my styled error page to transfer the user back to my standard login page.
So my problem is I cannot see what's wrong with my new password2.php. Can anyone help with this?
Here's the full new password2.php code:
<?php
ob_start();
include ('config.php');
include ('function.php');
$error_msg = "";
$token = $_GET['token'];
$userID = UserID($email);
$verifytoken = verifytoken($userID, $token);
// Sanitize and validate the data passed in
if (isset($_POST['submit'],$_POST['username'], $_POST['email'], $_POST['p'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$new_password = filter_input(INPUT_POST, 'new_password', FILTER_SANITIZE_STRING);
$retype_password = filter_input(INPUT_POST, 'retype_password', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);}
$new_password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($new_password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $db ->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
}
} else {
$error_msg .= '<p class="error">Database error</p>';
}
if($new_password != $retype_password) {
// Create a random salt
$salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
// Create salted password
$new_password = hash('sha512', $random_salt . $salt);
}
// Insert the new hashed password into the database
if ($insert_stmt = $db->prepare("UPDATE members SET password = ? WHERE id = ? ")) {
$insert_stmt->bind_param('si', $newpassword, $id);
// Execute the prepared query.
if (!$insert_stmt->execute()) {
header('Location: ../error.php?err=Database Registration failure: INSERT');
}
// Update recovery key
if ($insert_stmt = $db->prepare("UPDATE recovery_keys SET valid = 0 WHERE id = ? AND token = ? "));
$insert_stmt->bind_param('is', $id, $token);
// Execute the prepared query.
if ($insert_stmt->execute())
$msg = 'Your password has changed successfully. Please login with your new password.';
}else
{
header('Location: ../error.php?err=Registration failure in updating recovery key: INSERT'); }
{exit();}
?>
When the code above is run I get a blank page with the the correct token code shown in the site link.
This password2.php page has an include to a functions page which is shown below.
function checkUser($email)
{
global $db;
$query = mysqli_query($db, "SELECT id FROM members WHERE email = '$email'");
if(mysqli_num_rows($query) > 0)
{
return 'true';
}else
{
return 'false'; }
}
function id($email)
{
global $db;
$query = mysqli_query($db, "SELECT id FROM members WHERE email = '$email'");
$row = mysqli_fetch_assoc($query);
return $row['id'];
}
function generateRandomString($length = 25) {
// This function has taken from stackoverflow.com
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return md5($randomString);
}
function send_mail($to, $token)
{
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = '';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->SetFrom = '';
$mail->FromName = '';
$mail->addAddress($to);
$mail->addReplyTo('', 'Reply');
$mail->isHTML(true);
$mail->Subject = 'Company Password Recovery Instruction';
$link = 'x.php?email='.$to.'&token='.$token;
$mail->Body = "<b>Hi</b><br><br>You have just requested a new password for your company account with QBS Tax Submission. <a href='$link' target='_blank'>Click here</a> to reset your password. If you are unable to click the link then copy the hyper link below and paste into your browser to reset your password.<br><i>". $link."</i>";
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
return 'fail';
} else {
return 'success';
}
}
function verifytoken($id, $token)
{
global $db;
$query = mysqli_query($db, "SELECT valid FROM recovery_keys WHERE id = $id AND token = '$token'");
$row = mysqli_fetch_assoc($query);
if(mysqli_num_rows($query) > 0)
{
if($row['valid'] == 1)
{
return 1;
}else
{
return 0;
}
}else
{
return 0;
}
}
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, email, password, salt
FROM members
WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($id, $username, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$id = preg_replace("/[^0-9]+/", "", $id);
$_SESSION['id'] = $id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
if (!$mysqli->query("INSERT INTO login_attempts(id, time)
VALUES ('$id', '$now')")) {
header("Location: ../error.php?err=Database error: login_attempts");
exit();
}
return false;
}
}
} else {
// No user exists.
return false;
}
} else {
// Could not create a prepared statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
}
function checkbrute($id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time
FROM login_attempts
WHERE id = ? AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there have been more than 5 failed logins
if ($stmt->num_rows > 5) {
return true;
} else {
return false;
}
} else {
// Could not create a prepared statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
}
function login_check($mysqli) {
// Check if all session variables are set
if (isset($_SESSION['id'], $_SESSION['username'], $_SESSION['login_string'])) {
$id = $_SESSION['id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
FROM members
WHERE id = ? LIMIT 1")) {
// Bind "$id" to parameter.
$stmt->bind_param('i', $id);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
// If the user exists get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if ($login_check == $login_string) {
// Logged In!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Could not prepare statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
} else {
// Not logged in
return false;
}
}
function esc_url($url) {
if ('' == $url) {
return $url;
}
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%#$\|*\'()\\x80-\\xff]|i', '', $url);
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = (string) $url;
$count = 1;
while ($count) {
$url = str_replace($strip, '', $url, $count);
}
$url = str_replace(';//', '://', $url);
$url = htmlentities($url);
$url = str_replace('&', '&', $url);
$url = str_replace("'", ''', $url);
if ($url[0] !== '/') {
// We're only interested in relative links from $_SERVER['PHP_SELF']
return '';
} else {
return $url;
}
}
I believ this is where the issue is:
if (! $insert_stmt->execute())
$msg = 'Your password has changed successfully. Please login with your new password.';
}else{..}
if (! $insert_stmt->execute()) this means if the query fails echo that password fails.....
the reason your code always display Registration failure in updating recovery key: INSERT its because you instructed your code that when the query does not fail it must produce that.
And your code all of it is in mess, you need to clean it up.
Thi is how this should look.
if ($insert_stmt = $db->prepare("UPDATE recovery_keys SET valid = 0 WHERE userID = ? AND token = ? "));
$insert_stmt->bind_param('ss', $userID, $token);
// Execute the prepared query.
if ($insert_stmt->execute())
$msg = 'Your password has changed successfully. Please login with your new password.';
}else
{
$msg = "Password doesn't match";
header('Location: ../error.php?err=Registration failure in updating recovery key: INSERT'); }
{exit();}
Edit
Tried to clean up some of the mess in your code. Now this how should look.
<?php
ob_start();
include('config.php');
include('function.php');
$error_msg = "";
$token = $_GET['token'];
$userID = UserID($email);
$verifytoken = verifytoken($userID, $token);
// Sanitize and validate the data passed in
if (isset($_POST['submit'], $_POST['username'], $_POST['email'], $_POST['p'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$new_password = filter_input(INPUT_POST, 'new_password', FILTER_SANITIZE_STRING);
$retype_password = filter_input(INPUT_POST, 'retype_password', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);
}
$new_password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $db->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
}
} else {
$error_msg .= '<p class="error">Database error</p>';
}
if ($new_password != $retype_password) {
// Create a random salt
$salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
// Create salted password
$new_password = hash('sha512', $random_salt . $salt);
}
// Insert the new hashed password into the database
if ($insert_stmt = $db->prepare("UPDATE members SET password = ? WHERE id = ?")) {
$insert_stmt->bind_param('si', $new_password, $userID);
// Execute the prepared query.
if (!$insert_stmt->execute()) {
header('Location: ../error.php?err=Database Registration failure: INSERT');
exit();
}
// Update recovery key
if ($insert_stmt = $db->prepare("UPDATE recovery_keys SET valid = 0 WHERE userID = ? AND token = ? "));
$insert_stmt->bind_param('is', $userID, $token);
// Execute the prepared query.
if ($insert_stmt->execute())
$msg = 'Your password has changed successfully. Please login with your new password.';
} else {
$msg = "Password doesn't match";
header('Location: ../error.php?err=Registration failure in updating recovery key: INSERT');
exit();
}
?>
Important things you need to learn proper.
Update : here's the link
Prepared statements : link here
password hashing : link here
Your hashing method is very easy php does provide better and secure ways, please follow the links above.

Hashed password not coming out to what it should be (PHP)

So I'm trying to make a fairly simple login system, but for some reason the hashed password that is being sent to my database is not hashing correctly. I checked my database and the stored password is not what the sha256 hashed with the generated salt appended is not what it's supposed to be. Here's my code for generating the hash that's being uploaded to the database:
<?php
include "connection.php";
//Check Connection
if ($connect->connect_error) {
echo "Failed to connect to server: " . mysqli_connect_error();
}
//Reset all Checks
$username_exists = NULL;
$email_valid = NULL;
$passwords_match = NULL;
$password_acceptable = NULL;
$password_long_enough = NULL;
$password = NULL;
//Prepare Statements
//Check for Username Existing Statement
$check_username_match = $connect->stmt_init();
$sql_check_username = "SELECT id FROM $tablename WHERE username=?";
$check_username_match->prepare($sql_check_username);
$check_username_match->bind_param("s", $username);
//Insert Into Table Statement
$register_query = $connect->stmt_init();
$sql_register = "INSERT INTO $tablename (username, email, password, token, active, level) VALUES (?, ?, ?, ?, ?, ?)";
$register_query->prepare($sql_register);
$register_query->bind_param("sssssi", $username, $email, $hashedpassword, $token, $activated, $level);
//Execute When Form Submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$email = mysqli_escape_string($connect, $_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
//Check if Username Exists
$check_username_match->execute();
$check_username_match->store_result();
$numrows = $check_username_match->num_rows;
if ($numrows==0){
$username_exists = false;
} else {
$username_exists=true;
}
//Check if Passwords Match
if ($password==$confirm_password){
$passwords_match = true;
} else {
$passwords_match = false;
}
//Check if Email Address is Valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_valid = true;
} else {
$email_valid = false;
}
//Check if Passwords Contains Special Characters
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
//Check if Password is Long Enough
$password_length = strlen($password);
if ($password_length>8){
$password_long_enough = true;
} else {
$password_long_enough = false;
}
//Validate Password
if(!$uppercase || !$lowercase || !$number || !$password_long_enough || $password = '') {
$password_acceptable = false;
} else {
$password_acceptable = true;
}
//Register if all Validations Met
if(!$username_exists && $email_valid && $passwords_match && $password_acceptable){
//$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$token = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$activated="No";
$level = 0;
$hashedpassword = password_hash($password, PASSWORD_DEFAULT);
$register_query->execute();
$message = "Hello, welcome to the site.\r\n\r\nPlease click on the following link to activate your account:\r\nlocalhost/login_system/activate.php?token=".$token;
mail($email, 'Please Activate Your Account', $message);
header("Location: login.php");
}
}
?>
UPDATE: I changed my above code to reflect the changes I made with password_hash. However, the problem still persists.
This is my login php:
<?php
include("connection.php");
session_start();
//Reset Variables
$message = '';
$location = "/login_system/index.php"; //default location to redirect after logging in
$username = '';
$password = '';
//Check to see if user is newly activated; if he is display a welcome message.
if(isset($_GET['activated'])){
if($_GET['activated'] == "true"){
$message = "Thank you for verifying your account. Please login to continue.";
}
}
//Check to see if user is coming from another page; if he is then store that page location to redirect to after logging in.
if(isset($_GET['location'])) {
$location = htmlspecialchars($_GET['location']);
}
echo $location;
//Prepare login check statement
$check_login = $connect->stmt_init();
$sql = "SELECT id, password FROM $tablename WHERE username=?";
$check_login->prepare($sql);
$check_login->bind_param("s", $username);
//Execute Login Check
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$password = $_POST['password'];
$check_login->execute();
$check_login->store_result();
$numrows = $check_login->num_rows;
$check_login->bind_result($id, $match);
$check_login->fetch();
if ($numrows==1 && password_verify($password, $match)) {
$_SESSION['login_user'] = $id;
$goto = "localhost".$location;
header("location: $goto");
$message = "Success!";
} else {
$message="Username or password is not valid."."<br>".$match."<br>";
}
}
$connect->close();
?>
You should just feed the password you want to hash into PHP's password_hash();function. Like so...
$password = $_POST['password'];
$options = [
'cost' => 12,
];
echo password_hash($password, PASSWORD_BCRYPT, $options);
Then when you want to check if the password exists in the database use password_verify(); Like so...
$password = PASSWORD_HERE;
$stored_hash = HASH_HERE;
if (password_verify($password, $stored_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}

usercake updating field isn't working

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.

After selecting all from a certain row, is there a way to grab data from certain columns not defined?

So my SELECT statement is selecting all from a row in the users table. There is a column in that row labeled "user_level" and I want to use the data from that column to differentiate between an admin and a guest. Is there a way to use "user_level" (and maybe bind it to a session variable) without me having to write another SELECT statement?
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = :name and
user_password = :password");
$query->bindValue(":name", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
//user entered correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//user entered false details
$error = 'Incorrect details!';
}
}
}
You don't need no rowCount here.
as well as half of the duplicated and triplicated code.
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT user_level FROM users WHERE user_name = ? and user_password = ?";
$stm = $pdo->prepare($sql);
$srm->execute(array($username,$password));
$level = $stm->fetchColumn();
if ($level !== FALSE) {
//user entered correct details
$_SESSION['user_level'] = $level;
header('Location: index.php');
exit();
}
}
$error = 'Incorrect details!';

Categories