【问题标题】:Why does this failing PDO query return something other than `false`?为什么这个失败的 PDO 查询返回的不是 `false`?
【发布时间】:2012-09-15 23:48:02
【问题描述】:

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

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

我的问题:

鉴于我的查询没有通过,为什么我的 $id 的值是 0,而我已将其设置为 null,并且在查询失败时通常应该变为 false

【问题讨论】:

    标签: php mysql pdo prepared-statement


    【解决方案1】:

    这是你设置 ID 的地方

    $id=$dbh->lastInsertId(); 
    

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

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

    【讨论】:

      【解决方案2】:

      您忘记执行查询。

      添加:

      $dbh-&gt;execute();

      然后就可以拿到最后一个id了:

      $id=$dbh-&gt;lastInsertId();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-01
        • 2011-08-08
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        相关资源
        最近更新 更多