This PDO prepared statement returns false but does not throw an error

Simsevu picture Simsevu · Mar 25, 2010 · Viewed 26.3k times · Source

This code does not throw an error but the query fails, that is, the execute method returns false. How could that be?

require_once("Abstracts/DBManager.php");
require_once("UI/UI.Package.php");
class BlogDBM extends DBManager
{
     private $table = "blog_records";
     function saveRecord($title,$url,$desc,$feedId,$pubDate)
     {
      $PDO = $this->db->connect();
      try
  {

   $query = $PDO->prepare("
    INSERT INTO ".$this->table."
    (title,url,desc,feed_id,pubdate) VALUES
    (:title,:url,:desc,:feed_id,:pubdate)");
   $query->bindParam(":title", $title);
   $query->bindParam(":url", $url);
   $query->bindParam(":desc", $desc);
   $query->bindParam(":feed_id", $feedId, PDO::PARAM_INT);
   $query->bindParam(":pubdate", $pubDate, PDO::PARAM_INT);
   $query->execute();
   //return $PDO->lastInsertId();


  } catch(PDOException $e)
  {
   echo "Error " . $e->getMessage();

  }
  $PDO = NULL;
     }
}

Answer

WhoIsRich picture WhoIsRich · Jun 26, 2010

Just wanted to add to this, had similar frustrations from the lack of an error message.

To stop PDO from silently failing, you can set the error mode on the PDO connection.

$dbh = new PDO();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

There is also PDO::ERRMODE_WARNING if you want errors but still continue.