Home » Php » db2 – odbc last insert id for php script

db2 – odbc last insert id for php script

Posted by: admin February 25, 2020 Leave a comment


I’m trying the below script (script is in PHP, database is ODBC connection to db2 for as400) but I’m having issues due to the db2_last_insert_id being an unknown function.

I need to use the odbc setup for this script, and all other odbc functions work, but I can’t find a function in ODBC that replicates the db2_last_insert_id functionality

What is the best way for me to grab the id of the inserted row within the script itself?


$insertTable = "INSERT INTO testing_insert_php (name) VALUES ('Temp Name')";

$stmt = odbc_exec($DB2connPROD, $insertTable);
$ret =  db2_last_insert_id($DB2connPROD);

if($ret) {
    echo "Last Insert ID is : " . $ret . "\n";
} else {
    echo "No Last insert ID.\n";



How to&Answers:

Use VALUES identity_val_local() as your query. It will return a resultset with a single row and column.

You can’t mix and match DB access libraries. If you are using ODBC, then you have to use ODBC for everything associated with that connection. You can’t use ODBC to open a connection, and then DB2_ to operate on that connection.

In fact, both IBM_DB2 and PDO_IBM require a DB2 client, and the only one that works with DB2 for i is found in the DB2 Connect product. Unless the web server is running on IBM i itself.