PDO lastInsertId();问题php

时间:2012-09-26 06:48:28

标签: php pdo

我有一个父子关系数据库。我需要先插入父表然后获取ID,我将用它然后将数据插入子表。

以下是我用于插入数据库的代码片段。这是我第一次使用PDO类。我得到的错误;未定义属性:在非对象数据库:: $ db上调用成员函数lastInsertId()。我必须承认我是PHP的新手。谢谢


{

    public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS)
    {
        parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME, $DB_USER, $DB_PASS);
}

$this->db = new database(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);

    $this->db->insert('images', array(
        'image_userID' => $data['image_userID'],
        'image_date' => $data['image_date']
    ));

/**
 * insert
 * @param string $table A name of table to insert into
 * @param string $data An associative array
 */
public function insert($table, $data)
{
    $fieldNames = implode('`, `', array_keys($data));
    $fieldValues = ':' . implode(', :', array_keys($data));

    $sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)");

    foreach ($data as $key => $value) {
        $sth->bindValue(":$key", $value);
    }

    $sth->execute();

$result= $this->db->lastInsertId();
 return $result;
}

1 个答案:

答案 0 :(得分:7)

最后一个插入ID来自活动语句,而不是来自数据库句柄。因此,将代码的最后一行更改为:

$return = $sth->lastInsertId();
相关问题