9

When I insert a row, it increments the ID field using SERIAL.

How can I return the newly created ID number right after the insert?

(Database is Postgresql.)

Pacerier
  • 86,231
  • 106
  • 366
  • 634
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

5 Answers5

18
$db->Insert_ID();
Nirmal
  • 9,391
  • 11
  • 57
  • 81
7

This code works nicely:

$insertId = $adodb->getOne("INSERT INTO test (str) values ('test') RETURNING id");
user2116547
  • 71
  • 1
  • 2
3

Treat your INSERT the same as a SELECT and use RETURNING in your INSERT-query:

INSERT INTO foo (bar) VALUES('Doe') RETURNING id;

Fetch the result and you're done. Works since version 8.2

Frank Heikens
  • 117,544
  • 24
  • 142
  • 135
2

Insert_ID() in adodb returns empty value or in some case it return 0.

The postgresql I worked on is in 9.1 version.

$_sql = 'INSERT INTO '.$_table.' (';
$_sql .= implode(', ',$arr_fld_names);
$_sql .= ") VALUES ('";
$_sql .= implode("', '",$arr_fld_values);
$_sql .= "')";

if ($echo){
    echo $_sql;
}

$_return = $this->Execute($_sql);
$this->mLastInsertedId = $this->mConn->Insert_ID(); // Keep track of the last inserted ID.

Edit: I have added a dirty way:

$_sql = 'INSERT INTO '.$_table.' (';
$_sql .= implode(', ',$arr_fld_names);
$_sql .= ") VALUES ('";
$_sql .= implode("', '",$arr_fld_values);
$_sql .= "') RETURNING id";

if ($echo){
    echo $_sql;
}

$_return = $this->Execute($_sql);
preg_match_all('/([\d]+)/', $_return, $ret_val);
$this->mLastInsertedId = $ret_val[0][0]; // Keep track of the last inserted ID.
askmish
  • 6,464
  • 23
  • 42
Roshan
  • 21
  • 2
0

I like to use adodb to avoid writing SQL. I need to insert a record on table1 with text1 and at same time a record on table2 with other data and the created ID on table1 as a reference. I like the idea of using transaction and AutoExecute

$db->StartTrans();
{
    $array_table1 = array('text_field'=>'text1');
    $db->AutoExecute("table1", $array_table1, 'INSERT');

    if ($lastid=$db->Insert_ID()) {
        $array_table2=array(
            'text_field'=>'other text',
            'id_of_table1'=>$lastid);
        $db->AutoExecute('other_table', $array_table2, 'INSERT');
    } else {
        $db->RollbackTrans();
    }

}
$db->CompleteTrans();
$result=$db->_transOK;

Autoexecute still lacks of an option for returning the Insert_Id()

Daniel Faure
  • 391
  • 6
  • 14