/    Sign up×
Community /Pin to ProfileBookmark

MySQL: Last ID From INSERT

Hi All,

The following script adds a record to my orders table and then re-queries for it’s ID:

[code=php]$q = “INSERT INTO orders (fields_here) VALUES (values_here)”;
query_database($q);
$q = “SELECT MAX(id) AS id FROM orders”;
$result = query_database($q);
$row = mysql_fetch_array($result);
echo $row[‘id’];[/code]

The problem I’m having is that sometimes the ID returned is 1 less than I’m expecting. For example, I might get an ID of 30000 when I’m expecting 30001.

I’ve tried tweaking the SELECT query but no success.

Does anyone have any others ideas about what’s going wrong?


Thanks,
dai.hop

to post a comment
PHP

6 Comments(s)

Copy linkTweet thisAlerts:
@nyxSep 28.2010 — Could you not use the PHP mysql_insert_id function to get the last inserted id?
Copy linkTweet thisAlerts:
@BelrickSep 29.2010 — [code=php]
$q = "INSERT INTO orders (fields_here) VALUES (values_here)";
$result = mysql_query($q, $host) or die(mysql_error());
$id = mysql_insert_id();
[/code]
Copy linkTweet thisAlerts:
@webdeveloper83Sep 29.2010 — Just use the mysql_insert_id(); as the others said. SELECT MAX(id) might return errors, because your database might have double posted data, deleted or wrong entrys...

By using mysql_insert_id(); you'll always get the last id that was created!
Copy linkTweet thisAlerts:
@dai_hopauthorSep 29.2010 — Thanks all. I'll research mysql_insert_id() then!
Copy linkTweet thisAlerts:
@BelrickSep 29.2010 — Programming is like most art forms.

Technique is more important than the tools ya use.

Almost always more than one way of doing things but usually only one best way.
Copy linkTweet thisAlerts:
@NihilisteOct 01.2010 — I like this:


Programming is like most art forms.

Technique is more important than the tools ya use.
[/QUOTE]
×

Success!

Help @dai_hop 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.7,
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,
)...