使用 Adodb for php/postgresql,插入后返回行 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2308811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Adodb for php/postgresql, return row ID after insert
提问by Nic Hubbard
When I insert a row, it increments the ID field using SERIAL.
当我插入一行时,它会使用 SERIAL 增加 ID 字段。
How can I return the newly created ID number right after the insert?
如何在插入后立即返回新创建的 ID 号?
(Database is Postgresql.)
(数据库是 Postgresql。)
回答by Nirmal
$db->Insert_ID();
回答by user2116547
This code works nicely:
这段代码运行良好:
$insertId = $adodb->getOne("INSERT INTO test (str) values ('test') RETURNING id");
回答by Frank Heikens
Treat your INSERT the same as a SELECT and use RETURNING in your INSERT-query:
将您的 INSERT 与 SELECT 一样对待,并在您的 INSERT 查询中使用 RETURNING:
INSERT INTO foo (bar) VALUES('Doe') RETURNING id;
INSERT INTO foo (bar) VALUES('Doe') RETURNING id;
Fetch the result and you're done. Works since version 8.2
获取结果,你就完成了。从 8.2 版开始工作
回答by Roshan
Insert_ID()
in adodb
returns empty value or in some case it return 0.
Insert_ID()
inadodb
返回空值或在某些情况下返回 0。
The postgresql
I worked on is in 9.1 version.
在postgresql
我的工作是在9.1版本。
$_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.
回答by Daniel Faure
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
我喜欢用adodb
避免写SQL。我需要用 text1 在 table1 上插入一条记录,同时在 table2 上用其他数据和在 table1 上创建的 ID 作为参考插入一条记录。我喜欢使用事务的想法和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()
Autoexecute
仍然缺乏退货的选择Insert_Id()