LMPX.COM |
Home | Linux | Mysql | PHP | XML | ||
|
|
|||
From: AlfredReinoldBaudisch@osu1.php.net Date: Mon Oct 6 18:21:58 2008 Subject: note 86178 added to pdo.lastinsertid
For PostgreSQL you can still use the old solution to return the last Id of an INSERT, selecting the currval of a table's id_sequence.
The code below shows a working function (which is easy adaptale into another class, etc).
<?php
// -------------------------
// Last Insert ID for PDO with PostgreSQL
// -------------------------
function pgsqlLastInsertId($sqlQuery, $pdoObject)
{
// Checks if query is an insert and gets table name
if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) )
{
// Gets this table's last sequence value
$query = "SELECT currval('" . $tablename[1] . "_id_seq') AS last_value";
$temp_q_id = $pdoObject->prepare($query);
$temp_q_id->execute();
if($temp_q_id)
{
$temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC);
return ( $temp_result ) ? $temp_result['last_value'] : false;
}
}
return false;
}
?>
Example of use:
<?php
// ... connects to a PostgreSQL DB
$pdoObject = new PDO('pgsql:host=localhost;dbname=mydb', 'user', 'pass');
$sql = 'INSERT INTO table (column) VALUES (\'some_value\');';
$result = $pdoObject->prepare($sql);
$result->execute();
echo 'Last Insert ID: ' . pgsqlLastInsertId($sql, $pdoObject);
?>
----
Server IP: 200.185.109.13
Probable Submitter: 200.138.54.180
----
Manual Page -- http://www.php.net/manual/en/pdo.lastinsertid.php
Edit -- https://master.php.net/note/edit/86178
Del: integrated -- https://master.php.net/note/delete/86178/integrated
Del: useless -- https://master.php.net/note/delete/86178/useless
Del: bad code -- https://master.php.net/note/delete/86178/bad+code
Del: spam -- https://master.php.net/note/delete/86178/spam
Del: non-english -- https://master.php.net/note/delete/86178/non-english
Del: in docs -- https://master.php.net/note/delete/86178/in+docs
Del: other reasons-- https://master.php.net/note/delete/86178
Reject -- https://master.php.net/note/reject/86178
Search -- https://master.php.net/manage/user-notes.php
| Navigate in group php.notes at sever news.php.net | |
| Previous | Next |
| © No Copyright You are free to use Anything |
Site Maintained by PHP Developer
Powered By PHP Consultants |