Part I of this tutorial, "Build a Shopping Cart Admin Tool for Your PHP Online Store," explored the PHP scripts for running the shopping cart on an online book store (Pleasure Reading Inc.). Three remaining scripts weren't covered, and one of them (change.php) is perhaps the most complex of all the scripts. As the name implies, the change.php script is responsible for enabling the customer to alter the details of a book after adding it to the shopping cart. This article covers the change.php script in detail, as well as the two remaining scripts for shopping cart administration.
So, how does change.php work? Well, the booklist.php script sends over a bookid (in the form of bid), which change.php uses to retrieve the details of the book. When I say details, I mean absolutely everything about the book, see the screenshot below:
When change.php has retrieved everything, it adds the information to a form on the page and the user then makes the changes that he or she wants and then clicks on the "Update Book Details" button. At that point, the code execution starts.
What makes this script so complex is that it updates all the tables and then accesses all the tables to retrieve information about a particular book. Let's take a look at the code:
Now, the first part of the PHP code initializes variables and then checks if a bookid has been submitted. If so, the variable is cleaned with the mysq_escape_string() function, and then the details about the book are retrieved from the books table. This is significant, because the books table contains among other things the genre ID, the author ID and the publisher ID. These IDs are then used to retrieve information about the book from all the other tables. So, it is absolutely critical that this query is run first.
Note that a couple of variables have been initialized. You will see how they are used as we move through the script.
The next section of the code basically runs various queries on various tables to retrieve information related to this book:
All of the information that is retrieved will then be used for display on the form. When the user has completed making the changes, the code will run through the PHP script and update all the tables in the same way that it did previously. But this time it will clean the form data before inserting it:
Except for the genre table, both the other tables are updated:
Also, note the $err variable settings when the query is successful and when it is not. This again is key to whether the main table will be updated or not.
The remaining code basically updates the books table and also adds an image file if it is loaded:
The actual HTML contains only the form. Just remember that the form header is written differently from the way it is normally written:
This is because the form makes a provision for file uploads. That's basically it for the change script.

Find a programming school near you