0

I want to insert data into a mysql database with orders for my site.

So i store the username and an auto increment order number in the database.

The question is, how i extract the order number out again.

I have tried this:

SELECT ordernumber FROM transactions WHERE.....

How to finsh this?

9 Answers9

1

you can use

SELECT LAST_INSERT_ID();

more info on http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Note that you cannot use the C API function to retrieve the value for LAST_INSERT_ID(expr) after executing other SQL statements like SELECT or SET. So when you do INSERT Statement and just after that you do

SELECT LAST_INSERT_ID();

it works but when there are other statements in the middle it will return 0 and the only way to get it is described bellow.

the other option is to sort DESC the table and get the first number

SELECT ordernumber FROM transactions ORDER By ordernumber DESC LIMIT 1;
Robert
  • 19,800
  • 5
  • 55
  • 85
0

just use mysql_insert_id function it will give you last inserted id.

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
0

call mysql_insert_id() function after the insert query executed code

kapil
  • 162
  • 5
0

It depends on what methods you are using to insert the data into the database.

For mysql_* functions, you can use the mysql_insert_id() function.

For PDO use and mysqli_*, see this answer: What is equivalent of mysql_insert_id(); using prepared statement?

Community
  • 1
  • 1
David
  • 2,053
  • 2
  • 16
  • 26
0

can also use LAST_INSERT_ID() or mysql_insert_id

swetha
  • 132
  • 5
0
$lastOrderNumber = mysql_insert_id();
$sql = "SELECT ordernumber FROM transactions WHERE ordernumber = $lastOrderNumber;";
pulsar
  • 986
  • 1
  • 9
  • 22
0

As said in the other answers you should use mysql_insert_id.

For example you can use this:

$sql = "INSERT INTO table VALUES ('username')";
$result = mysql_query($sql);
echo "ID of last inserted record is: " . mysql_insert_id();

The above will output this:

ID of last inserted record is: (The ordernumber here)

For more info about mysql_insert_id you can take a look here.

Daanvn
  • 1,254
  • 6
  • 27
  • 42
0

there is a function to know what was the last id inserted in the current connection

for example after inster data you can get as below

mysql_query('INSERT INTO transactions  VALUES(\'b\')');

$id = mysql_insert_id();
liyakat
  • 11,825
  • 2
  • 40
  • 46
0

Another way is to run a query

select max(ordernumber) as lastordernumber from transactions;

here, lastordernumber is the desired value.

tausun
  • 2,154
  • 2
  • 24
  • 36