PHP PDO UPDATE not updating data - php

I am having a tough time updating data using PDO. These are the two options that i've tried. None has actually updated the database, however.
Query 1:
$dateLastLoggedIn = date("Y-m-d H:i:s");
$username = mysql_real_escape_string($_POST['User']);
$sth = $dbh->prepare("UPDATE users SET dateLastLoggedIn = ? WHERE username = ?");
$sth->execute(array($dateLastLoggedIn,$username));
print_r($sth->queryString); just prints out UPDATE users SET dateLastLoggedIn = ? WHERE username = ?
Query 2:
$dateLastLoggedIn = date("Y-m-d H:i:s");
$username = mysql_real_escape_string($_POST['User']);
$sql = "UPDATE users SET dateLastLoggedIn = '".$dateLastLoggedIn."' WHERE username = '".$username."'";
$sth = $dbh->prepare($sql);
$sth->execute();
print_r($sth->queryString); prints out UPDATE users SET dateLastLoggedIn = '2012-08-03 13:36:32' WHERE username = 'testuser'
The second option generates the correct query but it doesn't actually update the data. I can manually run the generated script and it works, but not through the execute(). Anything i'm doing wrong? I'm still new to PDO, so it may be a simple fix.
SOLVED: see my last comment under the accepted answer.

getting connection :
function getConnection(){
$dbhost="127.0.0.1";
$dbuser="application";
$dbpass="password";
$dbname="abc";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
try {
$dbh = getConnection();
$sth = $dbh->prepare("UPDATE users SET dateLastLoggedIn = :dateLastLoggedIn WHERE username = :username ");
$sth->bindParam('dateLastLoggedIn',$dateLastLoggedIn);
$sth->bindParam('username',$username );
$sth->execute();
$dbh = null; // after done
} catch(PDOException $e) {// simple exception handling
error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
Also, try to wrap this in try catch to see the error

print_r($sth->queryString); just prints out UPDATE users SET dateLastLoggedIn = ? WHERE username = ?
That's what will happen with PDO prepared queries.
If you're using PDO, mysql_real_escape_string isn't going to work. At all. It requires an existing connection via mysql_connect. Your username value is effectively blank.

Related

Check status of previous MySQL query and execute next query

I want to execute multiple MySQL queries. Where the next query depends on the status of the previous one. I need to check the status of the query and in some cases also rowCount(). If the first query returns what I want the next query will be executed and so on. If one of them fail the whole process will be stopped.
I usually nest my queries inside of a try/catch block. Is there a better way to do this? Here is my code. I do not want you to fix my code just see it and give me any suggestions. I'm using PDO with MySQL 5.6.26.
Thanks
$updated = false;
//#1
$query = "select username, forgot_code, time, valid from forgot_requests where forgot_code = :forgot_code";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
$data = $run_query->fetch(PDO::FETCH_OBJ);
//13min = 780s
if($run_query->rowCount() == 1 && (time() - $data->time < 7800000) && $data->valid) {
//#2
$query = "update users set password = :password where username = :username";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
':username' => $data->username
));
//#3
$query = "update forgot_requests set valid = 0 where forgot_code = :forgot_code";
try {
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
//update
$updated = true;
} catch(PDOException $e) {}
} catch(PDOException $e) {}
}
} catch(PDOException $e) {}
I assume you want to enforce a valid database state with your pre cautions.
MySQL and PDO offer you the concept of transactions to ensure that a series of sql statements will only be executed all together.
Example
<?php
$db->beginTransaction();
// Query 2
$query = "update users set password = :password where username = :username";
$run_query = $db->prepare($query);
$run_query->execute(array(
':password' => password_hash($_POST['password'], PASSWORD_DEFAULT),
':username' => $data->username
));
// Query 3
$query = "update forgot_requests set valid = 0 where forgot_code = :forgot_code";
$run_query = $db->prepare($query);
$run_query->execute(array(':forgot_code' => $_POST['forgot_code']));
// All queries will be executed or no query will be executed
$db->commit();
?>
If you encounter any problems you can roll back a transaction:
<?php
$db->rollBack();
?>
Further information can be found in MySql manual: (http://dev.mysql.com/doc/refman/5.7/en/commit.html) and in php documentation (http://php.net/manual/de/pdo.begintransaction.php)

Query was empty with MySQL select Query

So I'm new to php and mysql and over the past few days have created a log in system using php and mysql. I am trying to make a function where a user can change their password with the following query:
$query2 = mysql_query("SELECT password FROM adminusr WHERE id =$idToChange");
$result = mysql_query($query2) or die($idToChange.mysql_error());
With SELECT statements you only select rows. To change them you need UPDATE. Consider using PDO because mysql_* functions are deprecated. Also try to hash your passwords and don't store them in plain text.
You need something like this:
$query2 = mysql_query("UPDATE adminusr SET password = '$new_password' WHERE id = '$idToChange'");
Using PDO
//Make the connection using PDO
try {
$conn = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
//Make your query
$sql = 'UPDATE adminusr SET password = :new_password WHERE id = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':new_password'=>$new_password, ':id'=>$idToChange));
EDIT answering to comment
Then you need to have also username and password fields at your form. So, you need four fields: username, oldPassword, newPassword, confirmNewPassword. Before the update statement you need to select the user having credentials username, oldPassword. If you find only one then you have to check if newPassword and confirmNewPassword match. If match then proceed to update. Otherwise print some error message.

PHP Prepare statement error

Fatal error: Call to a member function prepare() on a non-object in
/home/melazabi/public_html/assigment/The/include/process.php on line
15
// check if the username exists in the database
// line 15 is the one below:
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();
As per what you shown in your comment:
You're using a mysql_* based connection
$conn = mysql_connect('localhost','admin','admin') or die("error2"); mysql_select_db("admin") or die("error");
with a PDO query.
You need to use: (replace with actual DB credentials)
$dbname = 'admin';
$username = 'admin';
$password = 'admin';
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The error is telling you the your query failed for any number of reasons.
Your db connection failed, either authentication problem or complete failure to connect.
Your params are not defined correctly.
you can debug this by
print_r($statement->errorInfo());
this will give you what the error returned by sql was.
also make user variables are set. If i were to guess not having seen the rest of your code. you probably want $_POST['un'] and $_POST['pw']
echo $un;
echo $pw;
edit
connect to db:
$conn = new PDO('mysql:host='SERVERADDRESS';dbname=DBNAME;charset=utf8', 'USERNAME', 'PASSWORD');
then your query
$statement = $conn->prepare("select * from users where username=? AND password=?");
//prepare statment is to try to stop sql injection
$statement->bindParam(1, $un);
$statement->bindParam (2, $pw);
$statement->execute();

First run with PDO getting a Call to a member function bindParam() on a non-object error

This is my first run with PDO, not sure how much better it is than using mysqli but its part of a project I have to create.
Here is the code that is causing the message, all I am trying to do is update pieces of data within my db table.
<?php
//PHP Data Objects
try{
//Connect
$dbh = new PDO('mysql:host=localhost; dbname = company; charset=utf-8','root', 'bachi619');
} catch(PDOException $e){
echo $e->getMessage();
}
$id = 4;
$name = "logan";
$department = "Design";
$sth = $dbh->query("UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id");
//bind
$sth->bindParam(':id',$id);
$sth->bindParam(':lastname',$name);
$sth->bindParam(':department',$department);
$sth->execute();
?>
you have to use
$dbh -> prepare("UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id");
Use prepare for PDO, check this http://in3.php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare('UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id' );
The dsn should be non spaced
$dbh = new PDO('mysql:host=localhost;dbname=company','root', 'bachi619');
You need to prepare the SQL statement like this
$sth = $dbh->prepare( 'UPDATE employees SET department=:department,last_name=:lastname WHERE id=:id' );
Then bind the parameters
$sth->bindParam(':id',$id);
$sth->bindParam(':lastname',$name);
$sth->bindParam(':department',$department);
and finally execute the query
$sth->execute();

update mysql database table fields with a single mysqli statement query

I have a database table and i am updating the table columns this way.
$mysqli = new mysqli('localhost', 'root', '', 'db');
if (mysqli_connect_errno()) {
echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
return 'error';
}
$username = $data['username'];
$data['image'] = $this->replace_whitespace($data['image']);
foreach($data as $key=>$value){
$this->query = "UPDATE users SET $key=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if($this->statement){
$this->statement->bind_param('s', $value);
$this->statement->execute();
$this->statement->close();
}
}
Is it possible to update more than one table columns in one go. I tried this but in-vain.
$this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if($this->statement){
$this->statement->bind_param('sss', $value1, $value2, $value3);
$this->statement->execute();
$this->statement->close();
}
Is there a better way doing this?
$mysqli = new mysqli('localhost', 'root', '', 'db');
if (mysqli_connect_errno()) {
echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
return 'error';
}
$username = $data['username'];
$this->query = "UPDATE users SET fname=?, lname=?, email=?, tpin=?, image=?, address=? country=?, city=?, state=?, postal=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if ($this->statement) {
$this->statement->bind_param('ssssssssss', $data['fname'],$data['lname'],$data['email'],$data['tpin'], $data['file'], $data['address'],$data['country'],$data['city'],$data['state'], $data['post_code']);
$this->statement->execute();
$this->statement->close();
}
This is my real code.
Remove the "," after col3=?
This will fix the syntax error
$this->query = "UPDATE users SET col1=?, col2=?, col3=?, WHERE username='$username'";
You have an extra comma, meaning your SQL is reading "WHERE" as another column and everything gets messed up.
$this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
Should work fine.
In response to the comment below, this is the correct way of going about it, so it must be a faulty variable somewhere, what error messages are you getting? (If any)
It could also be that one of the parameters you are binding is not a string. Regardless, we'd need a more in-depth example.
Is it possible to update more than one table columns in one go
Yes. Actually, updating many fields in one query is a very core feature of any DBMS. You can always expect it to be supported.
I tried this but in-vain.
Well, you have to try more, like we all do. After all, it's your job.
Two notes regarding your "real" code:
You have to bind ALL variables in the query, not only some of them
you have to configure mysqli to report errors:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I assume it works the same way as putting new values into the database.
Update a row mysql in php

Categories