Evaluate DB Query

Permalink
Sorry for this basic question, but I just can't for the life of me figure this out.

Given this code:
$db = Loader::db();
$vals = array($newpass,$userid,$oldpass); 
$sql = 'UPDATE myAccountUsers SET password=? WHERE userid=? AND password=?';
$posttodb = $db->query( $sql , $vals );


How do I test if the update was successful? I need to return a failed if the record did not update.

Thanks!

 
jordanlev replied on at Permalink Reply
jordanlev
The definition of "successful" in this case could mean different things. If the query is invalid or the database can't be connected to or something like that, then you can check like this:
$posttodb = $db->query($sql, $vals);
if ($posttodb === false) {
  //you have an error
  echo $db->ErrorMsg();
} else {
  //no error
}


BUT it sounds like you have some other definition of "success", meaning that as far as the database and the code is concerned, everything worked properly -- but it didn't affect the data in the way that you wanted. If that's the case, there's no way for the code to know on its own whether it was "successful" or not -- so what you need to do is run another query after the first one to see if you got the desired results (so you could do a "SELECT" query and compare the result to what you were hoping it would be).

By the way, it is very bad practice to store user passwords in plain text in your database. Why aren't you using Concrete5's built-in users and groups system, which handles all of this for you (and in a much more secure way)?
tciweb replied on at Permalink Reply
Thanks for your response! Yeah I get what you mean on the definition of successful statement. I was really trying to see if there was an update at all. This is what I went with and it works great for my purpose.
$db->query( $sql , $vals );       
return $db->affected_rows();


As far as the users and groups, they wanted this single page module to be separate from the content management system users and groups, and yeah they are encrypted passwords, just used the original posted code to get the point across, not the whole function.