MYSQL PDO update datetime does nothing [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
Tried for an hour already. Help pls. Basically i want to update lastlogin column(MYSQL datetime) every time a user login. There is no error message and no update is happening. What is going on?
db.php
<?php
// These variables define the connection information for your MySQL database
$username = "root";
$password = "root";
$host = "localhost";
$dbname = "rofl";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
main.php
<?php
include("DB/db.php");
if(!empty($_POST)){
$query = "
SELECT
userID,
password,
salt,
email
FROM user
WHERE
userID = :username
";
$query_params = array(
':username' => $_POST['useridforlogin']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['passwordforlogin'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
date_default_timezone_set('Asia/xxxxxx');
$timestamp = date('Y/m/d h:i:s a', time());
$query2 = "UPDATE user SET lastlogin= ':lastlogin' where userID = ':username'";
$query_params2 = array(
':lastlogin' => $timestamp,
':username' => $_POST['useridforlogin']
);
try {
$stmt2 = $db->prepare($query2);
$result2 = $stmt2->execute($query_params2);
} catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }

I think the problem comes from your date format.
Try replacing 'Y/m/d h:i:s a' by 'Y/m/d h:i:s' (removed the a)

Related

update field when user logs using pdo

This is my code:
date_default_timezone_set('UTC');
$now = date('l jS \of F Y h:i:s A');
$host = 'localhost';
$dbname = 'myDB';
$username = 'james';
$paswword = '12345';
$dsn = 'mysql:host='. $host .';dbname='. $dbname;
try
{
$connect = new PDO($dsn, $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$connect->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
$message = $e->getMessage()."<br>";
die();
}
$sql = 'SELECT * FROM people WHERE email = :email && password = :password';
$stmt = $connect->prepare($sql);
$stmt->execute(['email' => $email, 'password' => $pass]);
$result = $stmt->fetch();
if($result)
{
$_SESSION["username"] = $post->firstname;
$_SESSION["id"] = $post->id;
$sql = 'UPDATE people SET last_log_date = :now && WHERE id = :id';
//error happens here
$stmt = $connect->prepare($sql);
$stmt->execute(['last_log_date' => $now, 'id' => $_SESSION["id"]]);
$connect = null;
header("location:welcome.php");
}
else
{
$connect = null;
$_SESSION["err_msg"] = 'The password or email does not match';
header("location:loginForm.php");
}
?>
My code will check to see if the user logged in correctly but when I go to update the last_log_date I get a fatal error everytime. I don't understand why I cannot update the field after fetching it. The error says something like SQLSTATE[42000]: Syntax error or access violation:.
How can I properly update the fields after the user has logged in. Please any help would be appreciated
You should bind the right named parameter which is now.
$stmt->execute([':now' => $now, ':id' => $_SESSION["id"]]);
The && before your where clause has nothing to do here. Remove it (check SQL syntax)

Password verify using PDO returns nothing

I'm trying to create a login page but when I try and log in I get a blank page returned, I get no errors either. I want to return a success or failure message based on the outcome of the login script. Where am I going wrong?
Login page:
try {
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = : username LIMIT 1";
$query = $dbh->prepare( $sql );
$query->execute( array( ':username'=>$username ) );
$results = $query->fetchAll( PDO::FETCH_ASSOC );
foreach( $results as $row ){
if(password_verify($_POST['password'], $password)){
echo 'verified';
}
else
{
echo 'not verified';
}
}
The page to create a user:
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
//sets type to '1' which is used for a user.
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?, type= '1'");
$stmt->execute([$username, $email, $hash]);
echo "<p>Thank you for registering!</p>";
There is a space between the colon and "username"
'username = : username'
^
There should not be any spaces and to read as :username
A few lines below you are using:
array( ':username'=>$username )

PDO Login System not working

I know I'll get a bunch of down-votes, but I am new to PDO and need to make a login system for a little web application. I can't seem to get it right:
<?php
include 'Config.php';
$username = strtolower($_POST['username']);
$password = md5($_POST['password']);
$hidden = $_POST['hidden'];
$submit = $_POST['submit'];
$host = $config['mysql']['host'];
$mysql_user = $config['mysql']['user'];
$mysql_pass = $config['mysql']['pass'];
$db = $config['mysql']['db'];
if(isset($username) && isset($password) && isset($submit) && !isset($hidden)) {
try {
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
$objQuery = $objDatabase->prepare("SELECT * FROM users WHERE username=:username");
$objQuery->bindValue(':username', $username);
$objQuery->execute();
$row = $objQuery->fetch(PDO::FETCH_ASSOC);
if(!empty($row)) {
if($username == $row['username'] && $password == $row['password']) {
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $row['username'];
header('Location: i/');
} else
header('Location: index.php?err=true&type=1');
} else
header('Location: index.php?err=true&type=2');
} catch(PDOException $e) {
die($e->getMessage());
}
}
?>
I always get error 2 - account not found. I'm logging in with user "test" and password "test". In the database is an account with username "test" and the password is an MD5 hash of "test".
Your sql statement is wrong:
SELECT * FROM users WHERE username=':username'
You should not put your placeholder in quotes as now it is taken literally by mysql.
It should be:
SELECT * FROM users WHERE username=:username
You should also tell PDO to throw exceptions:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$objDatabase = new PDO("mysql:host=" . $host . ";dbname=" . $db, $mysql_user, $mysql_pass, $opt);
So that it will tell you when something goes wrong.
Edit: As noted by #LozCheroneツ you also need to execute the query before you can fetch a row:
$objQuery->bindValue(':username', $username);
$objQuery->execute();

PHP failing to login - could it the sha256 hashing?

Trying to develop a simple CRUD application piecing together tutorials from the net, just now I'm working on the login and this is proving to be a slight problem. I can register a user and it will add a record to the database, but when I try logging in it fails every time. My code sample is below, any help would be greatly appreciated.
Index.php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
userid,
username,
password,
salt,
email
FROM wt_users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password == $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['users'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
config.php
// These variables define the connection information for your MySQL database
$username = "*******";
$password = "***********";
$host = "*********";
$dbname = "********";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
loggedin.php
require("config.php");
if(empty($_SESSION['users']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
Plan is to display a CRUD interface once the user has logged in, but for the moment I can't get them logged in..

PHP validation using PDO not working

I am new to PDO. I have included validation in the following code but it doesnt seem to work and no message appears if users enter the wrong username/password. Please show me where I am going wrong. I have numerous times to get this working but no luck. Thanks
<?php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
Config.php
<?php
// These variables define the connection information for your MySQL database
$username = "xxxx";
$password = "xxxx";
$host = "xxxxxxx";
$dbname = "xxxxxx";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>

Categories