Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO lastInsertId(); issue php

Tags:

php

pdo

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;
}
like image 935
denn Avatar asked Sep 26 '12 06:09

denn


People also ask

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

How can I get last inserted record in MySQL using PHP?

$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.

What is PDO method in PHP?

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.

How check PDO query is successful in PHP?

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.


1 Answers

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();
like image 89
JvdBerg Avatar answered Sep 22 '22 15:09

JvdBerg