简体   繁体   English

PDO lastInsertId(); 问题php

[英]PDO lastInsertId(); issue php

I have a database with a parent child relationship. 我有一个父子关系数据库。 I need to first insert into the parent table then get the ID, that I would use to then insert data into the child table. 我需要先插入父表然后获取ID,然后我将用于将数据插入子表。

The following is snippets of the code I am using to insert into the database. 以下是我用于插入数据库的代码片段。 This is my first time using PDO class. 这是我第一次使用PDO类。 The errors I am getting; 我得到的错误; Undefined property: and Call to a member function lastInsertId() on a non-object database::$db. 未定义的属性: 在非对象数据库:: $ db上调用成员函数lastInsertId()。 I must admit am I fairly new to PHP. 我必须承认我是PHP的新手。 Thank you 谢谢


{

    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;
}

The last insert ID comes from the active statement , and not from the database handle. 最后一个插入ID来自活动语句 ,而不是来自数据库句柄。 So change the last line of your code to this: 因此,将代码的最后一行更改为:

$return = $sth->lastInsertId();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM