PHP PDO not executing SQL command - php

I'm working on a PHP script to reset a user's password. I have an email and a token check setup so that those two must be valid before the user is allowed to reset. So far, everything works up to the point where I insert the password into the database. Here's the code for my PDO (I broke the SQL query at those parts so it's easier to glance over):
try {
$sql = "UPDATE users
SET password=:password, sessionTime=:sessionTime, sessionID=:sessionID
WHERE sessionID=:sessionID";
$update = $con->prepare($sql);
$update->bindValue("password", hash("sha256", $password . $salt), PDO::PARAM_STR);
$update->bindValue("sessionID", "0", PDO::PARAM_STR );
$update->bindValue("sessionTime", "0", PDO::PARAM_STR );
$update->execute();
echo "<br /> Successfully updated the password!";
} catch(PDOException $e) {
throw new Exception('something went wrong with the password reset', 0, $e);
}
$salt and $password are defined prior to this, and when I run the script, it outputs Successfully updated the password!, however, nothing changes in my database. When I copy and paste the query into phpMyAdmin and change the :name parameters to actual strings, it works perfectly (updating my database) and doesn't return any errors - also, I'm not getting anything in php_error.log, so I'm not really sure why this isn't working.
Any help would be appreciated, thank you.

Can you run the script with errorInfo like below and report the results:
<?php
try {
$sql = "UPDATE users
SET password=:password, sessionTime=:sessionTime, sessionID=:sessionID
WHERE sessionID=:sessionID";
$update = $con->prepare($sql);
$update->bindValue("password", hash("sha256", $password . $salt), PDO::PARAM_STR);
$update->bindValue("sessionID", "0", PDO::PARAM_STR );
$update->bindValue("sessionTime", "0", PDO::PARAM_STR );
$update->execute();
var_dump($update->errorInfo());
echo "<br /> Successfully updated the password!";
} catch(PDOException $e) {
throw new Exception('something went wrong with the password reset', 0, $e);
}

Related

PHP/mySQL - INSERT INTO not working but also no error

one specific php/mydql command is not working. the sql will not be executed, nor do I get an error message. The sql command executed by HEIDI SQL gives me no error. Query before this command are executed correct. Only this one specific isn't working. I wrote it done one by one as the others which worked perfect before. Heres the code:
$sql = "INSERT INTO users (username,password,email) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($username, $hash, $email));
The connection.php file code:
global $conn;
$config = [
$dbname = "mysql:host=localhost; dbname=starwardb;",
$login = "root",
$password = ""
];
try {
$conn = new PDO(...$config);
} catch (Exception $ex) {
echo "ERROR: " . $ex;
}
Thank you for any advice!
The mistake was, that the hashing of the password extends the string. The Database length of the password was by 50. I have increased it to 64 and now it works fine.
From: https://stackoverflow.com/revisions/45147068/3

Undefined variable when attempting to store messages PHP PDO

I have a variable called $message which outputs the message contents when an action is performed to give the user some feedback however I keep getting an undefined variable error from PHP.
It's really weird because sometimes it works fine and other times it just returns the error message. Can anyone tell me what I'm doing wrong.
Just to confirm, this is a variable which is purely for storing messages. This isn't something which is "POSTED' from a form. Its generated within the PHP file itself.
An example of its usage:
<?php
session_start();
include "../includes/db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = $_SESSION['username'];
$sql = $db_conx->prepare("SELECT username, user_record_id FROM login_details
WHERE username = :username");
$sql->bindParam(':username', $username, PDO::PARAM_STR);
$sql->execute();
$user_record_id = $sql->fetchColumn(1);
$proposal = $_POST['proposal_id'];
$insertRec = $db_conx->prepare("INSERT INTO student_saved (proposal_id, user_record_id) VALUES (:proposal, :user_record_id)");
$insertRec->bindParam(':user_record_id', $user_record_id, PDO::PARAM_STR);
$insertRec->bindParam(':proposal', $proposal, PDO::PARAM_STR);
$insertRec->execute();
$message = "<p class='text-success'> Proposal Added To Your Favourites <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
if( $e->getCode() == 23000)
{
$message = 'This proposal has already been saved to your favourites';
}
else
{
$message = $e->getMessage();
}
}
die($message);
?>
Any help would be much appreciated!

try/catch in php not printing anything out

Hey Everyone it has been awhile wince I've worked with try/catch blocks but I would like to start using them again just for purpose of error handling and proper practices. My code is below,
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try {
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//if the connection fails the try/catch block will pick it up
if (!$conn) {
throw new PDOException('Fatal error on connection');
} else {
//prepare and exexcute the query to match the codes up
$stmt = $conn->prepare("SELECT email_code, active from primarydb.user WHERE email_code = ?");
$stmt->bindParam(1, $email_code, PDO::PARAM_STR, 32);
//check to make sure that the statment executes properly
if (!$stmt->execute()){
throw new PDOException("PDO ERROR ON EXECUTION:\n" . $stmt->errorInfo());
} else { //statement has not failed
//get the row count
$count = $stmt->rowCount();
//traverse the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//there can only be one!
if ($count != 1 || $row['active'] != 0) {
//generate error message
throw new PDOException("Wrong Code");
} else {
echo "working";
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->brindParam(1, 1, PDO::PARAM_INT);
$stmt->bindParam(2, $email_code, PDO::PARAM_STR, 32);
if (!$stmt->execute()) {
throw new PDOException("We're sorry but we can not update your profile at this time, plesae try again later. If this problem persists please contact customer service.");
} else {
print "Your account has now been activated and it is ready to use!";
}
}
}
}
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
I would like to know why I am not getting any of the error messages, and then how do I fix this problem so that I can avoid making the same problems again in the future. If there is something that is missing or if more information is needed please let me know. Otherwise I think it is pretty straight forward.
ADDITIONAL INFO: I have putt a message that says working at each block of if/else and the one it finally stops showing up at is when I check if($count != 1 || $row['active'] != 0)
UPDATE
<?php
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try{
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->bindParam('is', $a = 1, $email_code);
if($stmt->execute()){
print "Your account has now been activated and it is ready to use!";
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
?>
Generated new code, I don't want to get off topic, but I would like a complete solution to this problem. I am now getting the following error
Strict Standards: Only variables should be passed by reference in C:\inetpub\wwwroot\mjsite\login\complete_registration.php on line 14
SQLSTATE[HY000]: General error: 2031
Thoughts?
Please read this first line from the PDOException documentation:
Represents an error raised by PDO. You should not throw a PDOException
from your own code.
Just throw and catch regular old Exceptions. This would also catch a PDOException which inherits from it.
This also gives you a much better way to distinguish between actual exception thrown by PDO and your own exceptions. By the way, it would seem you have a number of cases where you are redundantly throwing exception when PDO would have encountered an error and thrown an exception anyway. Only the first exception will be caught, so in many of those cases, your throw would never be executed.
Also why bother with the SELECT before the update at all? YOu are basically just wasting a query because you aren't doing anything with the selected information. Perhaps just go straigth for update and handle cases where email_code doesn't exist.

Converting deprecated PHP SQL commands to PDO

Recently looking through some old files and realised that they are now deprecated. I've tried converting them into the newer PDO variant, but I'm stuck on something. Here's the code:
<?php
$team=$_POST['team'];
$user=$_POST['user'];
$dbHandle=new PDO("mysql:host=localhost;dbname=databasename;","user","password",array(PDO::ATTR_EMULATE_PREPARES=>false));
$query=$dbHandle->prepare("INSERT INTO tablename VALUES(?,?,?)");
if(!is_numeric($user)){
echo "Error message 1";
}elseif($user=="123"){
echo "Error message 2";
}else{
$query->execute(array($user,$team,"pending"));
if(mysql_affected_rows()>0){
echo "Success message";
}else{
echo "Error message 3";
}
}
?>
Nothing I've tried seems to get the success message. It looks like most of the code is working, because it always ends up giving me the third error message every time, and I can confirm that nothing has been added to the database. Not shown above are the three lines of code for enabling all PHP error messages, but the page isn't throwing up any such messages.
Also, while I'm at it, I'm still not entirely familiar with PDO, but from the way I understood it, it's much more secure. From what I have above, are there any security risks, and if so, how should I fix them?
EDIT: The code is currently as thus:
<?php
$team=$_POST['team'];
$user=$_POST['user'];
$dbHandle=new PDO("mysql:host=localhost;dbname=databasename;","user","password",array(PDO::ATTR_EMULATE_PREPARES=>false));
$query=$dbHandle->prepare("INSERT INTO tablename VALUES(?,?,?)");
if(!is_numeric($user)){
echo "Error message 1";
}elseif($user=="123"){
echo "Error message 2";
}else{
$query->execute(array($user,$team,"pending"));
if($query->rowCount()>0){
echo "Success message";
}else{
echo "Error message 3";
}
}
?>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,"user","password", $opt);
$stm = $pdo->prepare("INSERT INTO tablename VALUES(?,?,?)");
$stm->execute(array($_POST['user'],$_POST['team'],"pending"));
echo "Success message";
The problem is that mysql_affected_rows() function is not PDO, you should use ->rowCount() method to know the value of affected rows. Also, I would preffer to add parameters in a separated instruction specifying the correct type with constants like PDO::PARAM_INT and PDO::PARAM_STR, so you can avoid errors:
$query=$dbHandle->prepare("INSERT INTO tablename VALUES(?,?,?)");
if(!is_numeric($user)){
echo "Error message 1";
}elseif($user=="123"){
echo "Error message 2";
}else{
$status = "pending";
$query->bindParam(1, $user, PDO::PARAM_INT);
$query->bindParam(2, $team, PDO::PARAM_STR);
$query->bindParam(3, $status, PDO::PARAM_STR);
$query->execute();
if($query->rowCount() > 0){
echo "Success message";
}else{
echo "Error message 3";
}
}

PHP MYSQL if statement on PDO result

Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.
Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql = 'SELECT COUNT(*) FROM wl_user
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute("USE $dbname");
}
catch (PDOException $e)
{
$error = 'Error searching for user. ' . $e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
$row = $s->fetch(PDO::FETCH_NUM);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Any help would be appreciated
For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.
Also, you are trying to catch an exception but apparently don't tell PDO to throw them.
And you are catching it only to echo a message, which is a big no-no.
I've explained the right way recently in this answer
If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.
Try this
try
{
$pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
array(PDO::ATTR_PERSISTENT => true));
$sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.

Categories