php/mysql - PDO prepared insert, does not work, an

2019-04-03 23:35发布

问题:

This question already has an answer here:

  • My PDO Statement doesn't work 1 answer

I really have NO idea of what to do with this now, i have been staring at it for hours, and reqritten it.. i can't get it to work!.

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;
     }
}

回答1:

I'm pretty sure that MySQL chokes on the desc field name - it is a reserved word. You'd have to put it into "`" quotes or, better, change the field name.

As for error reporting, use the errorInfo method. You can make PDO actually output the result of a failed query in the exception, but the default behaviour - I think - is to throw an exception only if the query can't be made at all, but it doesn't fail if the query is faulty.



回答2:

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.



回答3:

I was also facing that error.

I used print_r($con->errorInfo()); it gives me 0000 in 0th key of array.

Then I matched all column names and figured out that I am using wrong field name.

This saves my day.



回答4:

It also happens when you use PDOStatement::bindValue() with PDO::PARAM_BOOL. Solution: just switch to PDO::PARAM_INT.



回答5:

Similar problems can occur when someone turns/leaves off the DB autoincrement on the main id field.



回答6:

i struggled with this silent insert fail this week. and here's the solution that worked for me. i was not calling commit on the transaction, so the insert was put into the pending state but was never completed on the database - hence no error. this was trickier because the PDR db wrapper in this project is a static class so it doesn't automatically close

solution: make sure to call commit on the PDO handle after the insert / update / delete actions - or on page close.

$PDO->exec("COMMIT;");