为什么这个失败的PDO查询会返回除“false”之外的其他内容?

时间:2012-09-15 23:48:02

标签: php mysql pdo prepared-statement

注意:我的问题是查询失败的原因。

使用WampServer和phpMyAdmin。

以下是代码:

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;

我尝试使用和不使用try和交易。无论如何,我得到以下内容:

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

原因是我需要在反引号中封装表名。但有趣的部分(对我来说)还有待......

var_dumps的输出如下:

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

我的问题:

鉴于我的查询未通过,为什么0的{​​{1}}值为$id,我设置为null,通常应为false查询失败?

2 个答案:

答案 0 :(得分:2)

这是您设置ID

的地方
$id=$dbh->lastInsertId(); 

仅仅因为您的其他查询失败,并不意味着这个是。返回的值根据不同的驱动程序而有所不同,但我假设如果最近没有添加行,则数据库返回0。

尝试在函数开头调用此函数,甚至在尝试INSERT之前调用它,它也将返回0。

答案 1 :(得分:1)

您忘了执行查询。

添加:

$dbh->execute();

然后你可以得到最后一个id:

$id=$dbh->lastInsertId();