I have a database with a parent child relation. I need to insert the parent table first, then get the identifier that I will use to then insert the data into the child table.
The following are snippets of the code that I use to insert into the database. This is my first experience using a PDO class. The errors that I receive; Undefined property: and Calling the member function lastInsertId () in the database without an object :: $ db. I have to admit, I'm pretty new to PHP. Thanks 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']
));
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;
}
source
share