I got a problem for my profile page in my login system. When I want to update the user's username and email, I can only update one of the two. Look where I putted the points. If I use username it only updates the username and the same goes for the email.
Here is my code:
function updateProfile($db, $errors)
{
$id = $_SESSION['user']['id'];
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$field_check_query = "SELECT * FROM users WHERE username='$username' email='$email'";
$result = mysqli_query($db, $field_check_query);
$field = mysqli_fetch_assoc($result);
// Checks if username is already taken
if ($field) {
if ($field['username'] === $username) {
array_push($errors, "Gebruikersnaam is al reeds ingenomen");
}
// Checks if email is already taken
if ($field['email'] === $email) {
array_push($errors, "E-mailadres is al reeds ingenomen");
}
}
if (count($errors) == 0) {
if (isset($_POST['.......'])) {
$query = "UPDATE users SET username='$username' email='$email' WHERE id=$id";
mysqli_query($db, $query);
header('location: profile.php?profileeditedsuccesfully');
die($query);
}
}
}
Add AND to WHERE in Select:
$field_check_query = "SELECT * FROM users WHERE username='$username' AND email='$email'";
Add comma to separate the pairs in Update.
=$query = "UPDATE users SET username='$username', email='$email' WHERE id=$id";
Related
I have a login form who data are stored in a table users. I also have another table that stores the login date and time.
The table users (id, username, password)
The table user_login (id, user_id, login_date)
The code I tried:
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$name = $_SESSION['username'];
$row=mysqli_fetch_array($results);
$user_id= $row['id'];
$date = date('Y-m-d');
$checkdate= "SELECT id from user_login WHERE user_id='$user_id' AND DATE(login_date)='$date'";
$check=mysqli_query($db, $checkdate)or die(mysqli_error($db));
if(mysqli_num_rows($check)==1){
$updatedate="UPDATE user_login set date= $date where id=$user_id";
mysqli_query($db,$updatedate)or die(mysqli_error($db));
}
else{
$insertdate="INSERT INTO user_login (user_id, login_date) values($user_id, $date)";
mysqli_query($db,$insertdate)or die(mysqli_error($db));
}
// $_SESSION['success'] = "You are now logged in";
header('location: profile.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
The above code just adds date and time every time I login. But I want to save the date only once per day.
Here's one idea.
You could save date into your user_login table and then you can check and compare it
Before inserting into your user login table you would then check it.
Get id of the user from $results.
And check table:
$date=date('Y-m-d');
Select id from user_login where user_id = $user_id and Date(login_date) = $date
If there is a record just update date
$cur_date=date('Y-m-d');
Update user_login set date=$cur_date where id=$user_login_id
else insert one
INSERT INTO user_login (user_id, login_date) values($user_id, $cur_date);
I hope you understand the logic.
I hope you are using mysqli_escape_string in order to prevent from sql injection.
Don't use md5 for password encryption use bcrypt or other secure encryption functions.
here is working version of your code. Don't use it in production.
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$name = $_SESSION['username'];
$row = mysqli_fetch_array($results);
$user_id = $row['id'];
$date = date('Y-m-d');
$datetime = date('Y-m-d H:i:s');
$checkdate = "SELECT id from user_login WHERE user_id='$user_id' AND DATE(login_date)='$date'";
$check = mysqli_query($db, $checkdate) or die(mysqli_error($db));
if (mysqli_num_rows($check) == 1) {
$updatedate = "UPDATE user_login set login_date='$datetime' where user_id=$user_id and DATE(login_date)='$date'" ;
mysqli_query($db, $updatedate) or die(mysqli_error($db));
} else {
$insertdate = "INSERT INTO user_login (user_id, login_date) values($user_id, '$datetime')";
mysqli_query($db, $insertdate) or die(mysqli_error($db));
}
// $_SESSION['success'] = "You are now logged in";
header('location: profile.php');
die;
}else {
array_push($errors, "Wrong username/password combination");
}
}
this is just demonstration.
I'm working on implementing the ability for users to edit their passwords.
I'm using PASSWORD_BYCRYPT, and password_verify works fine after creating a user, but as soon as a user edits their password, it stops working.
Password change:
else if (isset($_POST["submitUpdateSettingsPW"])) {
$passwordText = $_POST["passwordChangeInput"];
$userID = $_SESSION["userID"];
$passwordNew = password_hash($passwordText, PASSWORD_BCRYPT);
$sql = "UPDATE users SET password = '$passwordNew' WHERE id = '$userID';";
if (mysqli_query($conn, $sql)) {
header("location: settings.php");
}
else {
header("location: settings.php?message=Something+went+wrong.+You+may+not+have+the+permissions+to+do+this.");
}
}
Password creation
else if (isset($_POST["submitSignup"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$password = password_hash($passwordText, PASSWORD_BCRYPT);
$signupSQLCheck = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $signupSQLCheck);
if (mysqli_num_rows($result) == 0) {
$signupSQL = "INSERT INTO users set email = '$email', password = '$password'";
mysqli_query($conn, $signupSQL);
header("location: login.php?message=Your+account+is+active.+You+may+now+login.");
}
else {
header("location: login.php?message=This+email+is+already+registered.+Do+you+want+to+<a href = 'login.php'>login</a>?");
}
}
Password verify (works fine until changing password)
if (isset($_POST["submitLogin"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$loginSQL = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$result = mysqli_query($conn, $loginSQL);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
$hash = $row["password"];
if (password_verify($passwordText, $hash)) {
$_SESSION["user"] = 1;
$_SESSION["userID"] = $row["id"];
header("location: index.php");
}
}
else {
header("location: login.php?message=Incorrect+email+or+password.+Do+you+want+to+<a href = 'signup.php'>sign up</a>?");
}
}
Thanks in advance
I am a newbie and I was trying to create a login system using PHP and Mysql. After finishing registration form and adding few users, I was trying to create a login form. but it always returns false saying my your Your username or password is incorrect!. Below is my code. It will be great if someone could help me. Advance sorry if my doubt is tooo basic :/
<?php
session_start();
include '.\includes\functions\db.php';
?>
<?php
$username = strtolower(mysqli_real_escape_string($db, $_POST['username']));
$password = strtolower(mysqli_real_escape_string($db, $_POST['password']));
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['password'];
echo $hash_pwd;
echo $password;
$hash = password_verify($password, $hash_pwd);
if ($hash ==0) {
header("Location: ./index.php?error=check");
exit();
}else {
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$hash_pwd'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 0) {
echo "Your username or password is incorrect!";
}else {
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
}
//header("Location: ./index.php");
}
?>
and my registration page is as follows
<?php
//This Page is for registration of users
?>
<?php
// this php tag is for all includes
include '.\includes\functions\db.php';
?>
<?php
//print isset($_POST["submit"]);
//Getting all details inserted in form
if(isset($_POST["register"])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date('Y-m-d H:i:s');
//Encrypting and Securing recieved data
$username = strtolower(mysqli_real_escape_string($db, $username));
$firstname = strtolower(mysqli_real_escape_string($db, $firstname));
$lastname = strtolower(mysqli_real_escape_string($db, $lastname));
$email = strtolower(mysqli_real_escape_string($db, $email));
$password = strtolower(mysqli_real_escape_string($db, $password));
$encryptedpassword = password_hash($password, PASSWORD_DEFAULT);
//To check duplication of email ids
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db, $sql);
$row = mysqli_num_rows($result);//$row will return count of rows if any duplicate email ids are found
//To check duplication of usernames
$sql2 = "SELECT username FROM users WHERE username='$username'";
$result2 = mysqli_query($db, $sql2);
$row2 = mysqli_num_rows($result2);//$row2 will return count of rows if any duplicate usernames are found
//conditions to check what all duplicates are found
if($row > 0 && $row2 >0){
echo "Sorry...This email id and username is already taken!!!";
} elseif ($row > 0 ) {
echo "Sorry...This email id is already taken!";
} elseif ($row2 > 0) {
echo "Sorry...This Username is already taken!";
}else {
$query = mysqli_query($db, "INSERT INTO users (username, firstname, lastname, password, email, regdate) VALUES
('$username', '$firstname', '$lastname', '$encryptedpassword', '$email', '$date')");
if($query){
echo "Thank You! you are now registered.";
}
}
}
?>
The error in my code is because of password = '$hash_pwd' condition in my where clause. When i retried row with given username and later verified password using php, it works as intended. I guess password hashed in php using password_hash() cannot be retrived and verified like encryption. Anyway thanks for all of yours responses
I try to store the logged in attempts in the database, but it's not working. The loginAttempt columns is not updating. Also, I want to count the login attempts and block the user after 3 attempts.
How to fix this?
Here's the script:
session_start();
$loginDate = date("Y-m-d H:i:s");
$Error ="";
$successMessage ="";
if (isset($_POST['submit'])){
if ( !( $_POST['cnumber'] == "" && $_POST['password'] == "")){
$cnumber=$_POST['cnumber'];
$password= sha1($_POST['password']);
$cnumber = filter_var($cnumber, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($cnumber, FILTER_VALIDATE_INT)){
$con=mysqli_connect("localhost","test","password","login");
$result = mysqli_query($con, "SELECT * FROM Users WHERE contractNumber='$cnumber' AND password='$password'");
$data = mysqli_num_rows($result);
if($data==1){
$_SESSION['login_user']=$cnumber;
mysqli_query($con, "INSERT INTO `homecre1_testemailCheck`.`Logs`(`contractNumber`, `lastLogin`) VALUES ('$cnumber', '$loginDate')");
header('Location: profile.php');
} else {
mysqli_query($con, "UPDATE Logs SET loginAttempt = loginAttempt+1 WHERE contractNumber = '$cnumber'");
}
mysqli_close($con);
} else {
$Error ="Invalid Contract Number.";
}
} else {
$Error ="Contract Number or Password is Empty.";
}
Here's my database structure:
Users - table
id -PK
contractNumber
email
password
Logs - table
userId
contractNumber
lastLogin
loginAttempt
Your update query is missing SET and column contarct_number might be wrong: Your query should be like:
mysqli_query($con, "UPDATE Logs SET loginAttempt = loginAttempt+1
WHERE contractNumber = '$cnumber'");
I have 2 tables :
newpw_ask
email
code
users
id
username
password
email
sid
newpw_code
I have this PHP code:
$code = $_POST['code2'];
$email = mysql_query("SELECT email FROM pw_ask WHERE code='$code'");
if ($pass == $pass2) {
if ($email) {
$pass3 = md5($pass);
mysql_query("UPDATE users SET password='$pass3' WHERE email='$email'");
mysql_query("UPDATE users SET newpw_code='' WHERE email='$email'");
mysql_query("DELETE FROM pw_ask WHERE code='$code'");
header("Location: index.php?ret=pw");
} else {
echo 'Wrong code';
}
}
Only this query got executed:
mysql_query("DELETE FROM pw_ask WHERE code='$code'");
Also when I enter the right code, it says “Wrong code”.
You need to select the email correctly :
$sql = mysql_query("SELECT email FROM pw_ask WHERE code='$code'");
$row = mysql_fetch_array($sql);
$email = $row['email'];
btw you can also update multiple fields in 1 query :
mysql_query("UPDATE users SET password='$pass3' , newpw_code='' where email='$email'");