Retrieving the last inserted row

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
flycast
Forum Commoner
Posts: 37
Joined: Wed Jun 01, 2005 7:33 pm

Retrieving the last inserted row

Post by flycast »

I have a table that does not have any indexes defined and no auto incrementing fields. Even worse is that I can insert two rows with the same data in the fields so that the rows are exactly identical. If I use mysql_insert_id() I get a zero because it is missing an autoincriment field. Is there a reliable way I can get a piece of data that I can use later to go back and delete that specific row without modifying the table structure?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Retrieving the last inserted row

Post by Benjamin »

Yes but you should just add an auto_increment primary key and be done with it rather than write bandaid code.
flycast
Forum Commoner
Posts: 37
Joined: Wed Jun 01, 2005 7:33 pm

Re: Retrieving the last inserted row

Post by flycast »

astions wrote:Yes but you should just add an auto_increment primary key and be done with it rather than write bandaid code.
No. It is an add-in to a CMS. In order for the add-in to work it must deal with the tables that are already defined as is.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Retrieving the last inserted row

Post by Benjamin »

Adding fields to database tables should not affect the behaviour of code already using those tables.

Go ahead and post the table schema though. Then we can give you some specific answers to your issue.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Retrieving the last inserted row

Post by superdezign »

In order to do what you want, the clearest way is to add another column to it anyway. The column would make it easy to select the newest column. The best way to do it is to add an auto_increment id field. If there is some sort of unique id field in the table that you need to define the value of yourself, then you could simulate an auto_increment, but then why not just use an auto_increment id field?

The best method is either an auto_increment field or a date/datetime field. Both solutions require altering the database table, which is not a harmful process.
Post Reply