Understanding the PHP Function pg_Last_Oid
PHP provides a wealth of functions for us to use right out of the box. These built in functions are great for performing tasks that we might otherwise have to write custom code for. But if you want to get even more out of these built in functions then you need to understand the concepts behind them. Often these functions are scoped, meaning that they have different implications depending on the scope of where they are called from.
The function pg_last_oid() returns the OID assigned to the last inserted tuple (record) in a table. If the OID field is not present in a table, the programmer must call pg_result_status() to check for successful insertion. This function can also be used to get the name of a sequence in which a record was inserted. If the name of this sequence is unknown, it can be determined using the PostgreSQL 8.0 function pg_get_serial_sequence.
This is a simple example of how scope can affect the behaviour of a function. It is important to understand how to use pg_last_oid and other functions in the correct way to avoid getting surprises when you try to debug your application.
One thing to keep in mind when working with sequences is that each value emitted by the sequence is only guaranteed to be unique within this session. If someone else calls nextval on that same sequence at the same time, then they will get a different value. This is why it is good to either wrap all inserts in transactions or make use of another set of identifiers that are unique across sessions, such as user_id and timestamp.