Quite often, when creating an interactive form using PHP and MySQL, you’ll want to allow users to enter some details, save the form (first time) then reload the page with these settings intact. However, in order to perform an update on the next save, you need to have a unique value to reference the correct row in the database.
A simple example would be to allow users to insert some details about themselves, eg an address. If there’s no ID assigned, the MySQL would run an insert. The ID number would be created during the insert (auto-increment value).
if (!$id) {
mysql_query = "INSERT INTO table_name (name, address1, address2, postcode) VALUES ('$name', '$address1', $address2', '$postcode');
} else { ...
The next time your save the form, you want to be able to overwrite the existing entry, instead of creating a new row.
This would normally be done as follows:
... } else {
mysql_query = "UPDATE table_name SET name='$name', address1='$address1', address2='$address2', postcode='$postcode' WHERE id=$id";
}
Usually, when you save a form, you redirect the user to a different page with a success message, but if you’re building a complex form, you’ll probably want to give users an option to save as they go, and this means that on submitting the form, you’re loading the same page. So the problem is how do you reload the page after the first save and get the ID number from the record that’s been created?
Simple, you would use the mysql_insert_id(); command:
if (!$id) {
mysql_query = "INSERT INTO table_name (name, address1, address2, postcode) VALUES ('$name', '$address1', $address2', '$postcode');
$id=mysql_insert_id();
} else { ...
This command grabs the insert ID for the last record to be inserted by the current script, you can now assign this variable to your page for use when determining whether the page contains new details, or whether it should overwrite an existing record.

website design
December 17th, 2009 at 15:03
Good designs, i am surely going to refer and use in my website design practices.