无法获得上次插入ID

时间:2012-06-22 12:26:45

标签: php mysql pdo

我已从其中一个Google代码下载了以下代码,但问题在于获取最终插入ID。

请参阅run()功能

此方法用于运行自由格式的SQL语句,这些语句无法通过包含的delete,insert,select或update方法进行处理。如果未生成SQL错误,则此方法将返回DELETE,INSERT和UPDATE语句的受影响行数,或SELECT,DESCRIBE和PRAGMA语句的关联结果数组。

<?php

    class db extends PDO {

        private $error;
        private $sql;
        private $bind;
        private $errorCallbackFunction;
        private $errorMsgFormat;
        public $lastid;
        public function __construct($dsn, $user = "", $passwd = "") {
            $options = array(
                PDO::ATTR_PERSISTENT => true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            );

            try {
                parent::__construct($dsn, $user, $passwd, $options);
            } catch (PDOException $e) {
                $this->error = $e->getMessage();
            }
        }





        private function filter($table, $info) {
            $driver = $this->getAttribute(PDO::ATTR_DRIVER_NAME);
            if ($driver == 'sqlite') {
                $sql = "PRAGMA table_info('" . $table . "');";
                $key = "name";
            } elseif ($driver == 'mysql') {
                $sql = "DESCRIBE " . $table . ";";
                $key = "Field";
            } else {
                $sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';";
                $key = "column_name";
            }

            if (false !== ($list = $this->run($sql))) {
                $fields = array();
                foreach ($list as $record)
                    $fields[] = $record[$key];
                return array_values(array_intersect($fields, array_keys($info)));
            }
            return array();
        }

        private function cleanup($bind) {
            if (!is_array($bind)) {
                if (!empty($bind))
                    $bind = array($bind);
                else
                    $bind = array();
            }
            return $bind;
        }

        public function insert($table, $info) {
            $fields = $this->filter($table, $info);
            $sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ");";
            $bind = array();
            foreach ($fields as $field)
                $bind[":$field"] = $info[$field];
            return $this->run($sql, $bind);
        }

        public function run($sql, $bind = "") {
            $this->sql = trim($sql);
            $this->bind = $this->cleanup($bind);
            $this->error = "";

            try {
                $pdostmt = $this->prepare($this->sql);
                if ($pdostmt->execute($this->bind) !== false) {
                    if (preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
                        return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
                    elseif (preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql)) {
                       echo $this->lastInsertId();
                        return $pdostmt->rowCount();
                    }
                }
            } catch (PDOException $e) {
                $this->error = $e->getMessage();
                return false;
            }
        }




    }

    ?>

我用于插入记录的代码

    $insert = array(
        "userid" => 12345,
        "first_name" => "Bhavik",
        "last_name" => "Patel",
        "email" => "bhavik@sjmtechs.com",
        "password" => "202cb962ac59075b964b07152d234b70"

   $db->insert("users",$insert);
    echo $db->lastid;

1 个答案:

答案 0 :(得分:0)

insert()函数中,您从未设置$lastid,因此它永远不会具有正确的值。你需要这样的东西:

insert()功能中更改此行:

return $this->run($sql, $bind);

对此:

$rows = $this->run($sql, $bind);
$this->lastid = $this->lastInsertId();
return $rows;

即使没有上述修改,您也应该能够从课堂外访问lastInsertId(),如下所示:

$db->insert("users",$insert);
echo $db->lastInsertId();