- A (Very) Brief Introduction to SQL
- Connecting to the Database Server
- Selecting a Database
- Finding Out About Errors
- Adding Data to a Table
- Acquiring the Value of an Automatically Incremented Field
- Accessing Information
- Changing Data
- Building a Database Abstraction Class
- Summary
- Q&A
- Workshop
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 straight away, 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 ) values( '$domain', '$sex', '$mail' )"; mysql_query( $query, $link ); $id = mysql_insert_id(); print "Thank you. Your transaction number is $id. Please quote it in any queries.";