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.
The following is snippets of the code I am using to insert into the database. This is my first time using PDO class. The errors I am getting; Undefined property: and Call to a member function lastInsertId() on a non-object database::$db. I must admit am I fairly new to 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. So change the last line of your code to this:
$return = $sth->lastInsertId();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.