JDelage
JDelage

Reputation: 13672

Why does this failing PDO query return something other than `false`?

Note: My question is not why the queries are failing.

Using WampServer and phpMyAdmin.

Here is the code:

function createRecord(){
 $id=null;
 var_dump("ID: ",$id);
 $length=0;
 $dbh=$this->dbConnect();
 var_dump("DBH: ", $dbh);
 $dbh->beginTransaction();
 //try{
  var_dump("DBH: ", $dbh);
  //$dbh->beginTransaction();
  $insertInSets=$dbh->prepare("INSERT INTO 'sets' () VALUES ()"); // PDO Statement object.  ID is generated via autoincrement.
  var_dump("InsertInSets: ", $insertInSets);
  $id=$dbh->lastInsertId();
  var_dump("ID: ",$id);
  $insertInClosures=$dbh->prepare("INSERT INTO 'closures' (ancestor,descendant,length) VALUES (:ancestor,:descendant,:length)");
  var_dump("InsertInClosures: ", $insertInClosures);
  $insertInClosures->bindParam(":ancestor", $id); //<- This is line 22
  $insertInClosures->bindParam(":descendant", $id);
  $insertInClosures->bindParam(":length", $length);
  //$dbh->commit();
  exit;

I tried both with and without the try and the transaction. In any case I get the following:

Fatal error: Call to a member function bindParam() on a non-object in C:\wamp\www\Projetv0.2\Class_SetDAO.php on line 22

The reason for that is that I need to encapsulate the table names in backquotes. But the interesting part (to me) is still to come...

The outputs from the var_dumps are as follows:

string 'ID: ' (length=4)
null

string 'DBH: ' (length=5)
object(PDO)[8]

string 'DBH: ' (length=5)
object(PDO)[8]

string 'InsertInSets: ' (length=14)
boolean false

string 'ID: ' (length=4)
string '0' (length=1)

string 'InsertInClosures: ' (length=18)
boolean false

My question:

Given that my queries are not going through, why am I getting a value of 0 for $id, which I had set at null and which should normally become false upon query failure?

Upvotes: 1

Views: 127

Answers (2)

Rafael Figueiredo
Rafael Figueiredo

Reputation: 347

You forgot to execute the query.

Add:

$dbh->execute();

and then you can get the last id:

$id=$dbh->lastInsertId();

Upvotes: 1

andrewsi
andrewsi

Reputation: 10732

This is where you're setting ID

$id=$dbh->lastInsertId(); 

Just because your other queries are failing, it doesn't mean that this one is. The value returned varies according to different drivers, but I assume that your database is returning 0 if there are no recently added rows.

Try calling this right at the start of the function, even before you try to INSERT something, and it will also return a 0.

Upvotes: 2

Related Questions