Page 1 of 1

[SOLVED] Finding what was entered

Posted: Thu Apr 28, 2005 5:24 am
by rsmarsha
I have a query to enter an order into a DB, then if i want to find the number that was just entered i have to do another select query.

Is there a way of returning the value of a field that was just entered into the DB from an insert query?

Posted: Thu Apr 28, 2005 5:45 am
by phpScott
from mysql.com
When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement with mysql_query() and retrieving the value from the result set returned by the statement.
http://dev.mysql.com/doc/mysql/en/getti ... ue-id.html

Posted: Thu Apr 28, 2005 5:45 am
by rsmarsha
Great thanks, i'll look into it. :)

Posted: Thu Apr 28, 2005 5:49 am
by rsmarsha
If the query is :

Code: Select all

$enterorder = "INSERT INTO orders (orderno,username,dateadded,status,archive,exvat,price,payment,cpu,memory,motherboard,usb,hdd,hdda,raid,cdrom,dvd,dvdw,gcard,gcarda,sound,modem,network,floppy,cardreader,pccase,psu,osreq,firewire,monitor,keyboard,mouse,speakers,printer,virus,office,tvcard,onsite,q,discount,total,totalexvat,deldet) VALUES ('','$mail','$datejoined','$type','','$_POST[exvat2]','$_POST[price]','Finance','$_POST[cputext]','$_POST[memtext]','$_POST[boardtext]','$_POST[usbtext]','$_POST[hddtext]','$_POST[hddatext]','$_POST[raidtext]','$_POST[cdrtext]','$_POST[dvdtext]','$_POST[dvdrwtext]','$_POST[gcardtext]','$_POST[gcardatext]','$_POST[soundtext]','$_POST[modemtext]','$_POST[nettext]','$_POST[fddtext]','$_POST[mcrtext]','$_POST[casetext]','$_POST[psutext]','$_POST[osreqtext]','$_POST[firetext]','$_POST[montext]','$_POST[keytext]','$_POST[mousetext]','$_POST[sprtext]','$_POST[pritext]','$_POST[virtext]','$_POST[offtext]','$_POST[tvctext]','$_POST[onstext]','$_POST[q]','$_POST[discount]','$_POST[final]','$_POST[extotal]','$_POST[deldet]')";
	$enterq = mysql_query($enterorder, $db_conn) or die("Query enter order failed".mysql_error());
Then would i just use:

Code: Select all

used_id = mysql_insert_id($enterq);
?

Posted: Thu Apr 28, 2005 5:59 am
by phpScott
almost

Code: Select all

//after your query;
$sql = "SELECT LAST_INSERT_ID()";
$result = mysql_query($sql);

Posted: Thu Apr 28, 2005 6:07 am
by n00b Saibot
mysql_insert_id() is perfectly valid and shortcut alternate to what phpScott posted above. only thing is that you have it quite in wrong way. Its quite simply 1 liner :arrow:

Code: Select all

$id = mysql_insert_id();
As simple as that ;)

Posted: Thu Apr 28, 2005 6:21 am
by rsmarsha
thanks all :)

Posted: Thu Apr 28, 2005 6:25 am
by phpScott
doh, been awhile :oops:

Posted: Thu Apr 28, 2005 6:32 am
by n00b Saibot
phpScott wrote:doh, been awhile :oops:
Hey, no need man. :) We all are prone to this. Computers is such a field that you tend to forget and lag behind vastly if you aren't in touch. :wink: