/    Sign up×
Community /Pin to ProfileBookmark

Last ID when using Insert in MySql

I use an ID autonumber for the key in all my tables. When using “Insert” a new autonumber is created. I would like to obtain that number to use in my own rollback scheme.

Is there a php or mysql call that will return the ID when the insert is made OR does anyone have a method to obtain that ID?

TIA
Dick Deeds

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@JDM71488Jun 02.2007 — after connecting to and selecting a database, you could get the next auto_increment id that mysql will assign like so:
[code=php]$sql = mysql_query("SHOW TABLE STATUS LIKE 'table_name'");
$row = mysql_fetch_assoc($sql);

$item_number = $row['Auto_increment'];[/code]

or you could get the last one in the database by doing this:
[code=php]$sql = mysql_query("SELECT id FROM table_name ORDER BY id DESC LIMIT 1");
$row = mysql_fetch_assoc($sql);

$item_number = $row['id'];[/code]
Copy linkTweet thisAlerts:
@SheldonJun 02.2007 — or...
[code=php]
$query = mysql_query("INSERT INTO DATABASE") or die ("Database Error: ". mysql_error());
$last_id= mysql_insert_id($query);
echo($last_id);
[/code]
Copy linkTweet thisAlerts:
@lthJun 02.2007 — When insert a record into a table.you can get the autoincrement id by this function---mysql_insert_id();

e.g.
[CODE]mysql_query("INSERT INTO table1('name') values ('lth')");
$lastId = mysql_insert_id();
echo $lastId;[/CODE]
Copy linkTweet thisAlerts:
@DickDeedsauthorJun 02.2007 — Thanks much to all. They work!

Dick
×

Success!

Help @DickDeeds spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...