PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Related Books
Professional Linux Programming

Professional Linux Programming

As Linux increases its presence throughout the world as a target platform for professional...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

Migrating From MySQL To PostgreSQL In PHP

Replacing MySQL's Auto-increment

In MySQL, to create an auto-incrementing field called someID, you would do something like this:

Listing 9 listing-9.sql
create table myTable (
    someID      int             not null        auto_increment,
    name        varchar(255)    not null,
    primary key (someID)
);

In PostgreSQL, to get the same behaviour, you do:

Listing 10 listing-10.sql
create table myTable (
    someID      serial          not null,
    name        varchar(255)    not null,
    primary key (someID)
);

Using serial is basically a shortcut for the server to create an integer column, a sequence and a trigger. A sequence is a basically a function that returns an incremented number each time you call it, while a trigger is a function that is executed every time data is inserted or updated (in this case only inserts are relevant).

Tough to explain – it’s probably just as easy to read Serial Types in the PostgreSQL manual.

Finally, to fetch a newly inserted serial from a PostgreSQL table from PHP, you firstly need to call pg_last_oid(). This returns an OID (see the previous chapter), and you then need to select the serial column using the OID.

Here’s an example, using the SQL just above.

Listing 11 listing-11.php
<?php
    $result = pg_query($link, "insert into myTable (name) values ('phpRiot')");
    $lastOid = pg_last_oid($link);
 
    $result = pg_query($link, "select someID from myTable where oid = " . $lastOid);
    $row = pg_fetch_row($result);
 
    $newId = $row->someID;
?>

It’s a little bit longer to do than in MySQL, but you’re probably using some kind of database abstraction anyway, into which you could automate this into a single function call.

In This Article


Tagged in , ,