1

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

使用 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

我的问题:

鉴于我的查询没有通过,为什么我会得到一个0for的值$id,我已经设置了这个值,null并且通常应该false在查询失败时变为这个值?

4

2 回答 2

2

这是您设置 ID 的地方

$id=$dbh->lastInsertId(); 

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

尝试在函数的开头调用它,甚至在你尝试插入某些东西之前,它也会返回一个 0。

于 2012-09-15T23:54:30.580 回答
1

您忘记执行查询。

添加:

$dbh->execute();

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

$id=$dbh->lastInsertId();

于 2012-09-16T00:03:46.587 回答