How to tell when query executed successfully in PHP PDO?

How to tell when query executed successfully in PHP PDO?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Interpreting PDO Execution Results: Beyond Simple Success

When you execute a prepared statement in PHP using PDO, the execute() method returns a boolean value indicating whether the operation completed without throwing an exception. However, relying solely on this return value is often insufficient for determining if your specific business logic succeeded. The behavior differs significantly between INSERT, UPDATE, and SELECT operations, and understanding these distinctions is crucial for building robust applications.

Consider the specific scenario of updating user credentials:

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

In this snippet, $result will be true if the SQL syntax was correct and no exception occurred. It does not tell you if any rows were actually modified. This is a common source of subtle bugs where an application assumes data changed when it might not have.

The Trap of Boolean Returns

For INSERT statements, developers often check the return value or call lastInsertId() to confirm success. While execute() returning true guarantees no syntax errors or constraint violations occurred during execution, it doesn't inherently verify that a new row was generated if an ON DUPLICATE KEY UPDATE clause is involved. However, for standard inserts, checking the affected rows count provides clarity: $STH->rowCount().

For UPDATE statements like the one in your example, the situation is more nuanced. A return value of true simply means the database engine processed the query without crashing. If you are updating a record where UserID does not exist in the UserCreds table, or if the new values match the existing ones exactly (and your DBMS doesn't count such updates as affected), the query still executes successfully. The return value remains true, but zero rows may have been changed.

Checking Affected Rows

To distinguish between a "no-op" update and a successful modification, you must inspect the number of rows actually affected by the query. In PDO, this is done via the rowCount() method on the statement object.

$STH->execute($params);

if ($STH->rowCount() > 0) {
    // Rows were successfully updated
} else {
    // Either no matching rows existed or no changes were made
}

There is a critical caveat here regarding MySQL and MariaDB drivers. The rowCount() method returns the number of rows affected by an UPDATE statement only if the query was executed directly on the database connection, not via a transaction that hasn't been committed yet in some specific driver configurations, though generally, it works as expected for standard operations. For PostgreSQL, rowCount() typically returns -1 for SELECT statements and the number of rows affected for INSERT, UPDATE, and DELETE. Always verify the behavior against your specific database driver documentation if you are porting logic between systems.

Handling SELECT Statements

The approach for SELECT queries is fundamentally different because they do not modify data. Checking rowCount() on a SELECT statement in PDO will almost always return -1 (for PostgreSQL) or require special handling depending on the driver, even if rows were retrieved.

To determine if a SELECT executed successfully and returned data, you should rely on two factors:

  1. Exception Handling: Wrap your execution in a try-catch block to handle syntax errors or constraint violations immediately.
  2. Row Count Inspection: Check the actual number of rows fetched from the result set.
try {
    $STH = $this->_db->prepare("SELECT * FROM Users WHERE ID = :id");
    $STH->execute([':id' => $userId]);
    
    // For SELECT, we usually check if data was returned
    $users = $STH->fetchAll();
    
    if ($users === []) {
        // No rows found, but the query executed successfully
        echo "User not found.";
    } else {
        // Rows found
        echo "Found " . count($users) . " users.";
    }
} catch (PDOException $e) {
    // Handle syntax errors or connection issues
    error_log($e->getMessage());
}

Transactional Considerations

If your application relies on atomicity across multiple steps, remember that execute() returning true does not mean the transaction is committed. An UPDATE might succeed at the statement level but fail later in a multi-step transaction, rolling back changes automatically. In such cases, checking rowCount() gives you visibility into what happened within the current transaction context before it was either committed or rolled back.

Conclusion on Success Verification

Determining if a query executed successfully requires more than just checking the boolean return of execute(). For data-modifying statements like UPDATE, always inspect rowCount() to confirm that rows were actually changed. For SELECT statements, treat the execution success as confirmed by the absence of exceptions and verify data presence separately by checking the fetched result set size. This layered approach prevents silent failures where logic proceeds based on an assumption that data was modified when it wasn't.

Our network