Acquiring the Value of an Automatically Incremented Field
In our previous examples, we have added data to our database without worrying about the id column, which automatically increments as data is inserted. If we need the value of this field for a record at a later date, we can always extract it with a SQL query. What if we need the value immediately, though? It would be wasteful to look it up. Luckily, PHP provides mysql_insert_id(), a function that returns the value of an auto-incremented key field after a SQL INSERT statement has been performed. mysql_insert_id() optionally accepts a link resource as an argument. With no arguments, it works with the most recent link established.
So, if we want to tell a user the number we have allocated to her order, we could call mysql_insert_id() directly after adding the user's data to our database:
$query = "INSERT INTO domains ( domain, sex, mail ) ";
$query .= "values( '$domain', '$sex', '$mail' )";
mysql_query( $query, $link );
$id = mysql_insert_id();
print "Thank you. Your transaction number is $id.";