I know this has a simple answer that I should know, but for the life of me, can't remember. I have the following update statement in my code:

$stmt = $pdo->prepare("UPDATE `files` SET `filename` = ?, `md5` = ?, `filesize` = ?,`logtime` = now() WHERE `id` = ?");
$stmt->execute (array($isoname, $md5file, $isosize2, 1)) ;

How do I test if the update was successful?

Dani AI

Generated

Short summary and a robust pattern: PDO::execute() returns a boolean (true on success, false on failure). After a successful execute, use PDOStatement::rowCount() to learn how many rows were affected. A return of zero can mean either the WHERE matched no row or the UPDATE wrote the same values back (driver-dependent behavior). For SELECTs rowCount() is generally unreliable; for UPDATE/DELETE it is the usual check.

correctly pointed to the manual for execute, and discovered a syntax/logic issue (assignment vs comparison and treating the execute return as a row count). A clearer pattern is to enable exceptions, run the statement, then inspect rowCount() — or inspect errorInfo() if execute() is false. Example pattern:

try {
    $stmt = $pdo->prepare('UPDATE files SET filename = :fn, md5 = :md, filesize = :sz, logtime = NOW() WHERE id = :id');
    $ok = $stmt->execute([':fn'=>$isoname, ':md'=>$md5file, ':sz'=>$isosize2, ':id'=>1]);
    if ($ok === false) {
        $err = $stmt->errorInfo(); // driver message in $err[2]
    } else {
        $affected = $stmt->rowCount();
        // $affected > 0 => rows changed; 0 => no match or no change
    }
} catch (PDOException $e) {
    // handle exception
}

Practical tips: set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION to catch failures reliably, use strict comparisons (=== false) when checking execute(), and run a quick SELECT COUNT(*) if it is important to distinguish "no matching id" from "no changes made". See PDOStatement::rowCount and PDO error handling for details: PDOStatement::rowCount and PDO error handling.

Recommended Answers

All 3 Replies

Thanks for the reply, rproffitt. The problem is that if I test like in the following code, it errors on the if statement.

$stmt = $pdo->prepare("UPDATE `files` SET `filename` = ?, `md5` = ?, `filesize` = ?,`logtime` = now() WHERE `id` = ?");
$stmt->execute (array($isoname, $md5file, $isosize2, 1)) ;
      if $stmt = false
         exit;

Got it fixed. Replaced execute and if statement as follows:

$stmt = $pdo->prepare("UPDATE `files` SET `filename` = ?, `md5` = ?, `filesize` = ?,`logtime` = now() WHERE `id` = ?");
$count= $stmt->execute ($isoname, $md5file, $isosize2, 1 ) ;
   if ($count==0) 
      echo ("Std update failed");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.