Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell when query executed successfully in PHP PDO? [duplicate]

Tags:

How can I test to see if the following query executed successfully?

$STH = $this->_db->prepare("UPDATE UserCreds SET     VerificationString=:newVerificationString, ExpiryDate=:expiryDate      WHERE UserID = :userID;"); $STH->execute($params); 

I know I can use lastInsertId() when I'm adding new rows, but what about UPDATEs and SELECTs?

like image 602
Chuck Le Butt Avatar asked Mar 01 '12 17:03

Chuck Le Butt


People also ask

How check PDO query is successful in PHP?

To determine if the PDO::exec method failed (returned FALSE or 0), use the === operator to strictly test the returned value against FALSE. To execute an SQL statement that returns one or more result sets, call the PDO::query method on the PDO connection object, passing in a string that contains the SQL statement.

What does the Prepare method of a PDO object return when called successfully?

Return Values ¶ If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns false or emits PDOException (depending on error handling).

How check MySQL update query was successful in PHP?

Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all. Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row. However and on the rare occasion, >0 is required where this has also happened to me before; that is the reason of my answer.


2 Answers

The execute returns true on success and false on failure.

From Docs:

Returns TRUE on success or FALSE on failure.


So you can make sure query ran successfully like:

if ($STH->execute($params)) {   // success } else {   // failure } 
like image 108
Sarfraz Avatar answered Jan 18 '23 08:01

Sarfraz


execute() returns true/false based on success/failure of the query:

$status = $STH->execute($params);  if ($status) {    echo 'It worked!'; } else {    echo 'It failed!'; } 

One note: a select query which returns no rows is NOT a failure. It's a perfectly valid result that just happens to have NO results.

like image 32
Marc B Avatar answered Jan 18 '23 07:01

Marc B