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;
}
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
$last_id=mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 0 , 1" ); $row=mysql_fetch_assoc($last_id); echo $row['id']; Replace id by your id field name in database and table_name by your table name.
The PHP Data Objects (PDO) defines a lightweight interface for accessing databases in PHP. It provides a data-access abstraction layer for working with databases in PHP. It defines consistent API for working with various database systems.
To determine if the PDO::exec method failed (returned FALSE or 0), use the === operator to strictly test the returned value against FALSE. To execute an SQL statement that returns one or more result sets, call the PDO::query method on the PDO connection object, passing in a string that contains the SQL statement.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With