update field when user logs using pdo - php

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)

Related

Mysql not updating database

Can't seem to get the database to update. No errors are returned, all variables are being passed into the function and I've googled for hours probably even days. What's weird is that I have another function using the same code that's in this function that works fine...
public function updateCustomer($uname, $umail, $ushipping, $uchargeID, $udate, $ID)
{
try {
$dbhost = 'host';
$dbuser = 'app';
$db_name = 'order';
$dbpass = '';
$conn1 = mysql_connect($dbhost, $dbuser, $dbpass);
$sql1 = "UPDATE customers
SET name = $uname, email = $umail, shipping = $ushipping, shipped = 'NO', charge_ID = $uchargeID, date = $udate
WHERE ID = $ID";
mysql_select_db('orders');
mysql_query($sql1);
return ;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
As I mentioned in my comment above, mysql_query() will not throw any exception. You should check it's return value, and if false, echo out mysql_error(). The issue you're having most likely is because none of your variables are being escaped in the database. This is not valid syntax:
UPDATE customers SET name = example_username
You want this:
UPDATE customers SET name = 'example_username'
You're much better off to just tell MySQL where you want variables, and let MySQL to the magic using prepared statements. An example can be found here:
public function updateCustomer($uname, $umail, $ushipping, $uchargeID, $udate, $ID)
{
try {
$dbhost = 'host';
$dbuser = 'app';
$db_name = 'order';
$dbpass = '';
$db = new PDO("mysql:host={$dbhost};dbname={$db_name}", $dbuser, $dbpass);
$sql1 = "UPDATE customers
SET name = :uname, email = :umail, shipping = :ushipping, shipped = 'NO', charge_ID = :ucharge_id, date = :udate
WHERE ID = :id";
$stmt = $db->prepare($sql1);
$res = $stmt->execute([
'uname' => $uname,
'umail' => $umail,
'ushipping' => $ushipping,
'ucharge_id' => $uchargeID,
'udate' => $udate,
'id' => $ID
]);
return;
} catch (PDOException $e) {
echo $e->getMessage();
}
}

PDO Username validation if already exists

I have a problem with register form.My form works properly but whenever i try to insert username that already exists it doesn't shows any error.
here is my php register file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=dblogin", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
else{
$insert = $conn->prepare("INSERT INTO users (user_name,user_email,user_pass) values(:user_name,:user_email,:user_pass)");
$insert->bindparam(':user_name',$user_name);
$insert->bindparam(':user_email',$user_email);
$insert->bindparam(':user_pass',$hash);
$insert->execute();
}
}
catch(PDOException $e)
{
echo "connection failed";
}
?>
Thanks for your support
You are not executing the select statement. You need to bind params and execute the select statement, try this after the select statemnt.
$stmt->bindparam(':user_name',$user_name);
$stmt->execute();
public function usernameCheck($username)
{
$sql = "SELECT * FROM $this->table where username = :username";
$query = $this->pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
if ($query->rowCount() > 0) {
return true;
} else {
return false;
}
}
use this one in your project hope it will work... :)
missing } in if statement
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
}else{
}
I notice 4 things (2 of which have been mentioned by others):
First and smallest is you have a spelling error ($con instead of $conn) - don't worry it happens to the best of us - in you first $stmt query which means your select-results becomes NULL instead of 0 - so you rowCount find that it is not over 0 and moves on without your error message
Second you forgot to bind and execute the parameters in your first $stmt query which gives the same result for your rowCount results
Third always clean your variables even when using prepared statements - at a bare minimum use
$conn->mysql_real_escape_string($variable);
and you can with advantage use
htmlspecialchars($variable);
And fourth since you are not doing anything with the database (other than looking) you could simplify your code by simply writing:
$stmt = $conn->query("SELECT user_name FROM users WHERE user_name = '$user_name' LIMIT 1")->fetch();
as I said - no need to bind or execute in the first query
and as a general rule - don't use rowCount - ever - if you have to know the number of results (and in 99% of cases you don't) use count(); but if you as here just want to know if anything at all was found instead use:
if ( $stmt ) {
echo "exists!";
} else {
// insert new user as you did
}
Edit:
Also - as a side note - there are a few things you should consider when you initially create your connection...
Ex:
// Set variables
$servername = "localhost";
$username = "***";
$password = "***";
$database = "***";
$charset = 'utf8'; // It is always a good idea to also set the character-set
// Always create the connection before you create the new PDO
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
// Set default handlings as you create the new PDO instead of after
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // And add default fetch_mode
PDO::ATTR_EMULATE_PREPARES => false, // And ALWAYS set emulate_prepares to false
];
// And now you are ready to create your new PDO
$conn = new PDO($dsn, $username, $password, $opt);
Just a suggestion... happy trails

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();

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Login script using PDO extension not working

I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>

Categories