如何添加lastInsertId()?

时间:2012-09-19 11:37:13

标签: php sql pdo lastinsertid

  

可能重复:
  Can't get mysql_insert_id() to work

我想在此功能上使用 lastInsertId()打印最后插入的ID:

private function adduser() {

    if (!empty($this->error)) return false;

    $params = array(
        ':user_level' => parent::getOption('default-level'),
        ':name'       => $this->name,
        ':email'      => $this->email,
        ':username'   => $this->username,
        ':password'   => parent::hashPassword($this->password)
    );

    parent::query("INSERT INTO `login_users` (`user_level`, `name`, `email`, `username`, `password`)
                    VALUES (:user_level, :name, :email, :username, :password);", $params);

    $shortcodes = array(
        'site_address'  =>  SITE_PATH,
        'full_name'     =>  $this->name,
        'username'      =>  $this->username,
        'email'         =>  $this->email,
        'password'      =>  $this->password
    );

    $subj = parent::getOption('email-add-user-subj');
    $msg = parent::getOption('email-add-user-msg');
    $cid = parent::lastInsertId();

    if(!parent::sendEmail($this->email, $subj, $msg, $shortcodes))
        $this->error = _('ERROR. Mail not sent');

    $this->result = "<div class='alert alert-success'>" . sprintf(_('Successfully added user <b>%s</b> to the database. Credentials sent to user.'), $cid) . "</div>";

}

我添加了这个:

$cid = parent::lastInsertId();

然后在此处添加 $ cid

$this->result = "<div class='alert alert-success'>" . sprintf(_('Successfully added user <b>%s</b> to the database. Credentials sent to user.'), $cid) . "</div>";

但我一直在接受:

Fatal error: Call to undefined method Generic::lastInsertId() in

数据库连接如下所示:

public function dbConn() {

    include(dirname(__FILE__) . '/config.php');

    try {
        self::$dbh = new PDO("mysql:host={$host};dbname={$dbName}", $dbUser, $dbPass);
        self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    } catch (PDOException $e) {
        return '<div class="alert alert-error">'._('Database error: '). $e->getMessage() . '</div>';
    }


}

我应该如何正确添加 lastInsertId()

2 个答案:

答案 0 :(得分:2)

替换

$cid = parent::lastInsertId();

self::$dbh->lastInsertId();

... as(看起来像)你的连接对象存储在我们正在谈论的这个匿名类的dbh字段中。

答案 1 :(得分:0)

LastInsertID是PDO类的一种方法。

您在Generic上调用它,没有方法LastInsertID();