Download presentation
Presentation is loading. Please wait.
Published byLouisa Wright Modified over 8 years ago
1
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1 Wiley and the book authors, 2002 PHP Bible Chapter 17: Building Forms from Queries
2
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition2 Wiley and the book authors, 2002 Summary HTML forms for use with databases Basic form submission to a database Self-submission Editing data with an HTML form Data-driven forms
3
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition3 Wiley and the book authors, 2002 HTML forms Form handling is one of PHP's best features. The combination of HTML to construct a data-input form, PHP to handle the data, and a database server to store the data lies at the heart of all kinds of useful Web tasks You already know most of what you need to make good forms to be handled by PHP and a database Always use a NAME for every data entry element (INPUT, SELECT, TEXTAREA). These NAME attributes will become PHP "variable" names A form field NAME doesn't have to be the same as the database field name, but it's often a good idea You should usually specify a VALUE in your form field tags You can pass hidden variables from form to form using the HIDDEN INPUT field You can pass multiple variables in an array
4
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition4 Wiley and the book authors, 2002 Basic form submission to a database Submitting data to a database via an HTML form is straightforward if the form and form-handler are two separate pages *Newsletter_signup.html* Newsletter Signup Newsletter sign-up form Enter your email address and we will send you our weekly newsletter.
5
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition5 Wiley and the book authors, 2002 Basic form submission to a database (cont.) *formhandler.php* Newsletter Signup Status <?php if (!$_POST['email'] || $_POST['email'] == "" || strlen($_POST['email']) > 30) echo ' There is a problem. Did you enter an email address? '; else { mysql_connect("localhost", "phpuser", "sesame") or die("Failure to communicate with database"); mysql_select_db("test"); // Insert email address $mod_email = trim(mysql_escape_string($_POST['email'])); $query = "INSERT INTO mailinglist SET Email='$mod_email',Source='newsletter_signup.html'"; $result = mysql_query($query); if (mysql_affected_rows() == 1) echo ' Your information has been recorded. '; else { error_log(mysql_error()); echo ' Something went wrong with your signup attempt. '; } ?>
6
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition6 Wiley and the book authors, 2002 Basic form submission to a database (cont.) Having a separate form and form handler is a very clean design which can potentially be easier to maintain. However there are quite a few things you might want to do that can't be done easily with this model If something goes wrong with the submission, it's very difficult to redisplay the form with the values you just filled in. This is especially important with a user registration form, where you might want to check for unique e-mail addresses or matching passwords, and reject the registration with an error message if it doesn't pass the tests. Users may get annoyed if one type causes them to lose all the data they filled in Another situation where self-submission is better is when you need to submit the same form more than once (e.g. you are applying for auto insurance and you need to give the particulars of multiple cars) Separate form and form handlers also make it difficult to pull data from the database, edit it, and submit it – repeating the process however many times it takes for the user to be satisfied
7
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition7 Wiley and the book authors, 2002 Self-submission Self-submission refers to the process of combining one or more forms and form-handlers in a single script, using the HTML FORM standard to submit data to the script one or more times Self-submission is accomplished by specifying the same script name as the ACTION target in the form handler "> The single most important thing to remember about self- submitting forms is the logic comes before the display. In order to determine if this is the first time the script has executed, you can use a "stage" variable. This can be checking if the SUBMIT variable has a value or creating a hidden field in the form and checking if it has a value
8
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition8 Wiley and the book authors, 2002 Self-submission (example) * newsletter_signup.php * <?php if (isset($_POST['submitted'])) { if (!$_POST['email'] || $_POST['email'] == "" || strlen($_POST['email'] > 30)) $message = ' There is a problem. Did you enter an email address? '; else { // Open connection to the database mysql_connect("localhost","phpuser","sesame") or die("Can't communicate with database"); mysql_select_db("test"); // Insert email address $mod_email = trim(mysql_escape_string($_POST['email'])); $query = "INSERT INTO mailinglist SET Email='$mod_email',Source='newsletter_signup.html'"; $result = mysql_query($query); if (mysql_affected_rows() == 1) { $message = ' Your information has been recorded. '; $noform_var = 1; } else { error_log(mysql_error()); $message = ' Something went wrong with your signup attempt. '; }
9
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition9 Wiley and the book authors, 2002 Self-submission (example) // Show the form in every case except successful submission if (!$noform_var) { $thisfile = $_SERVER['PHP_SELF']; $message.= ' Enter your email address and we will send you our weekly newsletter. '; } ?> Newsletter Signup Newsletter sign-up form
10
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition10 Wiley and the book authors, 2002 Self-submission (cont.) The first time you load up this page, you should see a normal HTML form. If you submit without any data or with a string that's too long, you'll see an error message and the form again If something goes wrong with the database INSERT, you'll see an error message and the form again Only if the INSERT completes successfully will you not see the form again We only need to check for two states of the form (un-submitted or submitted) so we can either use the Submit button or use a hidden form field or session variable Another issue with self-submitted forms is navigation so you'll need to decide Whether the form can be resubmitted multiple times by the user Whether the user decides when to move on by clicking on a link or the form moves users along automatically Whether you need to pass variables on to the next page Whether you want to control where the user can go next or if you want to give the users multiple choices The answers to these questions will determine whether you need a control, another form, a simple link or button, or multiple links Make sure you adequately explain what is going to happen at each step
11
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition11 Wiley and the book authors, 2002 Editing database data with an HTML form PHP is brilliant at putting variables into a database, but it really shines when taking data from a database, displaying it in a form to be edited, and then putting it back in the database It's HTML-embeddings, easy variable-passing, and slick database connectivity are at their best in this kind of job TEXT and TEXTAREA are the most straightforward types of HTML input fields because they enjoy an unambiguous one-to- one relationship between identifier and content There is only one possible VALUE per NAME You just pull the data field from a record in the database and display it in the form by referencing the appropriate array value The following example takes a description out of the database and allows you to edit it
12
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition12 Wiley and the book authors, 2002 TEXT and TEXTAREA form example <?php // Open connection to the database mysql_connect('sql.gettelco.com','MGMT380b','MGMT380b') or die('Failure to communicate with database'); mysql_select_db('MGMT380b'); // check to see if this form had been submitted to itself if (isset($_POST['submit']) and $_POST['submit'] == 'Submit') { // Format the data $ItemID = trim($_POST['ItemID']); $Title = trim($_POST['Title']); $Description = trim($_POST['Description']); $update_query = 'UPDATE catalog SET '. 'Title = "'.mysql_escape_string($Title).'", '. 'Description = "'.mysql_escape_string($Description).'" '. 'WHERE (ItemID = "'.$ItemID.'")'; $result = mysql_query($update_query) or die('Couldn\'t execute query'); if (mysql_affected_rows() == 1) $success_msg = ' Your description has been updated '; else { error_log(mysql_error()); $success_msg = ' Something went wrong '; }
13
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition13 Wiley and the book authors, 2002 TEXT and TEXTAREA form example (cont.) // If form had not been submitted to itself (e.g. first time viewing it) elseif (isset($_GET['ItemID'])) {// Get the appropriate comment header and comment $ItemID = $_GET['ItemID']; $select_query = 'SELECT Title, Description FROM catalog '. 'WHERE (ItemID = "'.$ItemID.'")'; $result = mysql_query($select_query) or die('Unable to execute query'); $row = mysql_fetch_assoc($result); $Title = stripslashes($row['Title']); $Description = stripslashes($row['Description']); $success_msg = 'Editing Item ID: '.$ItemID; } else die ('Must set ItemID'); $this_page = $_SERVER['PHP_SELF']; $form_page = ' Description Edit Description Edit '.$success_msg.' '.$Description.' '; print ($form_page); ?>
14
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition14 Wiley and the book authors, 2002 TEXT and TEXTAREA form example (cont.)
15
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition15 Wiley and the book authors, 2002 SELECT form example The SELECT field type is perhaps the most interesting of all It can handle the largest number of options (as opposed to the CHECKBOX which can only have 2 options or the RADIOBUTTON which should have 5 or fewer options) It can also allow the user to select multiple options that can be passed back to the script using arrays Chapter 28 has even more exciting ways of combining SELECT statements in PHP with JavaScript In the following example we will use a SELECT field to pick which category a product belongs to and bring in the text for the select options from the related table
16
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition16 Wiley and the book authors, 2002 SELECT form example (cont.) <?php // Open connection to the database mysql_connect('sql.gettelco.com','MGMT380b','MGMT380b') or die('Failure to communicate with database'); mysql_select_db('MGMT380b'); // check to see if this form had been submitted to itself if (isset($_POST['submit']) and $_POST['submit'] == 'Submit') { // Format the data $ItemID = trim($_POST['ItemID']); $Title = trim($_POST['Title']); $Description = trim($_POST['Description']); $Category = $_POST['Category']; $update_query = 'UPDATE catalog SET '. 'Title = "'.mysql_escape_string($Title).'", '. 'Category = "'.$Category.'", '. 'Description = "'.mysql_escape_string($Description).'" '. 'WHERE (ItemID = "'.$ItemID.'")'; $result = mysql_query($update_query) or die('Couldn\'t execute query'); if (mysql_affected_rows() == 1) $success_msg = ' Your description has been updated '; else { error_log(mysql_error()); $success_msg = ' Something went wrong '; }
17
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition17 Wiley and the book authors, 2002 SELECT form example (cont.) // If form had not been submitted to itself (e.g. first time viewing it) elseif (isset($_GET['ItemID'])) {// Get the appropriate comment header and comment $ItemID = $_GET['ItemID']; $select_query = 'SELECT Title, Description, Category FROM catalog '. 'WHERE (ItemID = "'.$ItemID.'")'; $result = mysql_query($select_query) or die('Unable to execute query'); $row = mysql_fetch_assoc($result); $Title = stripslashes($row['Title']); $Description = stripslashes($row['Description']); $Category = $row['Category']; $success_msg = 'Editing Item ID: '.$ItemID; } else die ('Must set ItemID'); $this_page = $_SERVER['PHP_SELF'];
18
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition18 Wiley and the book authors, 2002 SELECT form example (cont.) $select_str = ' '; $select_result = mysql_query('SELECT * FROM categories') or die('?'); while ($row = mysql_fetch_assoc($select_result)) { if ($row['category_id'] == $Category) $select_str.= ' '. $row['description'].' '; else $select_str.= ' '. $row['description'].' '; } $select_str.= ' '; $form_page = ' Description Edit Description Edit '.$success_msg.' '.$Description.' '.$select_str.' '; print ($form_page); ?>
19
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition19 Wiley and the book authors, 2002 SELECT form example (cont.)
20
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition20 Wiley and the book authors, 2002 Multiple TEXT fields stored in an array In many instances, it's preferable to store multiple input fields into a single array If you have a catalog of items to display and you want to have TEXT fields to allow the Web user to enter the quantity of each item they want to purchase This example uses SESSION variables to pass information to other PHP scripts on the site (SESSION variables will be discussed more in chapter 27 but behave very similarly to GET and POST variables) This example also uses a separate form processing script so that the user could place orders from multiple pages that all get processed from the same script
21
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition21 Wiley and the book authors, 2002 Multiple TEXT fields stored in an array (example) Order entry page Order entry page Picture Item ID Title Description # In Inventory Price # Ordered <?php // Allow the use of session variables session_start(); // Open connection to the database $db_resource = mysql_connect('sql.gettelco.com','MGMT380b','MGMT380b') or die('Failure to communicate with database'); mysql_select_db('MGMT380b'); $sql = 'SELECT PictureURL,ItemID,Title,Description,Inventory,Price FROM catalog'; $result_id = mysql_query($sql) or die ('ERROR executing query');
22
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition22 Wiley and the book authors, 2002 Multiple TEXT fields stored in an array (example) while ($row = mysql_fetch_assoc($result_id)) { print (' '); print (' '.$row['ItemID'].' '); print (' '.$row['Title'].' '); print (' '.$row['Description'].' '); print (' '.$row['Inventory'].' '); print (' $'.$row['Price'].' '); if (isset($_SESSION['ordered_items']) and isset($_SESSION['ordered_items'][$row['ItemID']])) print (' <INPUT TYPE="text" NAME="ordered_items['.$row['ItemID']. '][quantity]" VALUE="'. $_SESSION['ordered_items'][$row['ItemID']]['quantity']. '" SIZE="4"> '); else print (' <INPUT TYPE="text" NAME="ordered_items['.$row['ItemID']. '][quantity]" VALUE="0" SIZE="4"> '); print (' '."\n"); } ?>
23
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition23 Wiley and the book authors, 2002 Multiple TEXT fields stored in an array (example)
24
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition24 Wiley and the book authors, 2002 Processing Multiple TEXT fields stored in an array Process order Items ordered <?php if (isset($_POST['ordered_items']) and is_array($_POST['ordered_items'])) { foreach($_POST['ordered_items'] as $ItemID => $value) $_SESSION['ordered_items'][$ItemID] = $value; } else die ('Did not order any items'); foreach ($_SESSION['ordered_items'] as $ItemID => $value) { if ($value['quantity'] > 0) { print(' '); print(' '.$ItemID.' '); print(' '.$value['quantity'].' '); print(' '); } ?> Continue shopping
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.