Building Database-Driven Applications with PHP and MySQL: Part II, Page 2
Adding and Editing Articles – article.php
There needs to be actual data in the database before we try to display anything, so a good place to start is with programming the file that will allow new articles to be added (and existing ones edited).
Fundamentally, adding and editing a news article is pretty much the same. The fields in the HTML forms for both processes would be identical, as would any validation on the incoming data. The primary differences between adding and editing occur at two different points:
1. After the form has been submitted, when the information is actually entered
into the database
2. In the edit screen, when the form must be pre-filled with the information from the article that is being edited.
Because of these differences, the first inclination might be to create two separate scripts to handle each task, including two separate forms. But by folding the code for both adding and editing articles into a single script and using a single form, chunks of redundant PHP and HTML scripting can be eliminated. The differences outlined above can be handled with relative ease just by using a series of well-placed if statements.
Here is the complete script.
Let's take a look at each part in detail.
Whether adding or editing an article, the HTML form will always be displayed first, since it is not encapsulated in any If Statements. It can be considered the default state or action of the script.
By placing an If Statement before the form, the execution of the script can easily be diverted, depending on the user's actions. In this case, the If Statement is used to check whether or not the form has been submitted.
If it has, we next need to determine whether an existing article is being edited, or a new one added. When an existing article is being edited, article.php will be called with a link that includes the primary ID number associated with that article. That ID number will be stored in a hidden field in the form (notice that it is referenced through the $_REQUEST array, since the id could be coming from the query string or the form), and passed along with the rest of the data when the form is submitted. To check and see if we're editing an existing article, we need only see if that hidden field is empty or contains a value.
At this point, the script either inserts the new entry into the database, or updates an existing one associated with the id number.
Once complete, a thank you message is generated and displayed. The form is outputted again, ready to add another article or make further changes to the selected one.