-2

可能重复:
无法让 mysql_insert_id() 工作

我想在这个函数上使用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()

4

2 回答 2

2

代替

$cid = parent::lastInsertId();

self::$dbh->lastInsertId();

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

于 2012-09-19T11:52:21.960 回答
0

LastInsertID 是 PDO 类的一个方法。

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

于 2012-09-19T11:43:18.490 回答