phppdolastinsertid

assign lastinsertid to a variable


I am basically a new programmer, with some Oracle experience from years gone by. I have a form that collects household and member information (which also has a dropdown with a database connection that connects to the database to retrieve a listbox of branches).

On the POST, it saves the information to the household and member tables in the database. The household is a parent table, so the record must be created first. I need to then retrieve the household.id ( a MySql auto increment field) to save to the member table, to associate the two.

On execution of the insert to the household table, it works fine. I printed the autoincrement field to check.

    $dbh->beginTransaction();
     $stmt->execute();
     print("lastinsertid is really = \n");
  //   $lastid->$dbh->lastInsertId();
     print $dbh->lastInsertId();

But I need to use it in the next statement so need to store it. When I do that (just change what is commented out), I get errors.

     $dbh->beginTransaction();
     $stmt->execute();
     print("lastinsertid is really = \n");
     $lastid->$dbh->lastInsertId();
  //   print $dbh->lastInsertId();

Errors:

PHP Notice: Undefined variable: lastid in C:\Users\Desktop\OECC\form with lastinsertid works.php on line 165
PHP Notice: Trying to get property of non-object in C:\Users\Desktop\OECC\form with lastinsertid works.php on line 165 PHP Fatal error: Call to a member function lastInsertId() on null in C:\Users\Desktop\OECC\form with lastinsertid works.php on line 165


Solution

  • $lastid = $dbh->lastInsertId()

    You're using -> instead of =