6

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

以下是我用来插入数据库的代码片段。这是我第一次使用 PDO 类。我得到的错误;未定义的属性:调用非对象数据库上的成员函数 lastInsertId()::$db。我必须承认我对 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;
}
4

1 回答 1

7

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

$return = $sth->lastInsertId();
于 2012-09-26T06:51:19.857 回答