Chapter 17 . Building Forms from Queries 315 (Web design software)

March 23rd, 2008

Chapter 17 . Building Forms from Queries 315 Another situation in which self-submission is a win is when you need to submit the same form more than once. Say you are applying for auto insurance online, and you need to give the particulars of three or four different cars. It s extra work for the user to submit the form, get a success message, and then have to click a button to go back to the form for car #2. This kind of navigation problem has no perfect solution, but in situations where there s a high probability of multiple submissions, self-submission causes fewer clickthroughs for your Web users. Finally, the separate form and form handler 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. A common example of this usage is a form to allow users to change their personal information, such as photos and bios, which people often like to fiddle with until they look exactly like the users want. If you want to make five small incremental edits to your user profile, you aren t going to want to go back and forth between form and form-handler ten times. Self-submission is accomplished by the simplest of means: specifying the same script name as the ACTION target in the FORM element like this:

Or, using a built-in feature unique to PHP: > Although you always have the option to just use the file s URL, the built-in $_SERVER[ PHP_ SELF ] variable is preferable. Then the file will continue to be handled correctly if you rename or move it (into a PHP-enabled directory, needless to say). $_SERVER[ PHP_SELF ] is the replacement for $PHP_SELF, which was available from all PHP scripts until version 4.2.0. The single most important thing to remember about self-submitting forms is: The logic comes before the display. If you re used to writing separate forms and handlers, this may seem a little counterintuitive at first but think of it this way: Because your form will look different or display variables based on interactions with the database, obviously these interactions must happen before the HTML for the page is output to the browser. After you construct a few selfsubmitting forms, logic-before-display will seem totally natural and painless. To use self-submission with controls, you will need to employ a more programmatic PHPwriting style what we term the maximum or medium style. Beginners may find this somewhat more difficult than a clear division between the functions of HTML (form display) and PHP (form handling). This can be mitigated somewhat by using the heredoc syntax, as we do in many of our examples. If you re a think-ahead type, by now you re wondering: BUT if the logic comes before the display, won t my script try to do the database operations before showing me the HTML form in the first place? Good question and an indication that we need some way to tell the script either We want to see the form now or We want to insert data into the database now. This What am I supposed to be doing now? bit is called a stage variable. It lets you keep track of how many times the form has submitted values to itself and, therefore, which stage of a multistep process you have reached. The cheapest stage variable to test for is the Submit button. You can name your Submit button and give it a value, which will be set as a PHP value only after the form is submitted at least once. The easiest way to demonstrate what we re talking about is by rewriting the previous form and form-handler as one self-submitting form, as we do in Listing 17-3. Caution Tip
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

314 Part II . PHP and MySQL Listing (Windows 2003 server web)

March 23rd, 2008

314 Part II . PHP and MySQL Listing 17-2 (continued) // Open connection to the database mysql_connect( localhost , phpuser , sesame ) or die( Failure to communicate with database ); mysql_select_db( test ); // Insert email address $as_email = addslashes($_POST[ email ]); $tr_email = trim($as_email); $query = INSERT INTO mailinglist (ID, Email, Source) VALUES(NULL, $tr_email , www.example.com/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.

; } } ?> Having a separate form and form handler is a very clean design that can potentially be easier to maintain. However, there are quite a few things you might want to do that you can t do easily with this model, caused by the difficulty of going back to the form from the form handler and the fact that variables are not available to both at the same time. For one thing, if something goes wrong with the submission, it s very difficult to redisplay the form with the values you just filled in. This is particularly important with something like a user registration form, where you might want to check for unique e-mail addresses or matching passwords and reject the entire registration with an error message if it doesn t pass the tests. People are going to be very annoyed if one little typo causes them to lose all the data that they just filled in and after one or two go-rounds, they will simply stop trying to register. The first step to solving all these problems is to combine form and handler into one selfsubmitting PHP script. Self-Submission Self-submission is not a new form of autoeroticism. It simply 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.
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Chapter 17 . Building Forms from Queries (Web design tools) 313

March 22nd, 2008

Chapter 17 . Building Forms from Queries 313 Figure 17-1: A form to insert data into a database Listing 17-2: Form handler for newsletter_signup.html (formhandler.php)

); /* Initialize the ID for the previous country. We will rely on the fact that Country.ID is numbered beginning with 1, so a previous ID value of zero means that the current country is the first */ $old_country_id = 0; /* loop through result rows (one per city) */ while ($row_array = mysql_fetch_row($result_id)) { $country_id = $row_array[0]; /* if we have a new country */ if ($country_id != $old_country_id) { /* set up country info */ $continent = $row_array[1]; $country_name = $row_array[2]; /* if there was a previous country close the city datum and country row */ if ($old_country_id != 0) print( \n ); /* start a row for the new country, and begin the city table datum */ print( ); print( ); print(

Newsletter sign-up form

30) { echo

There is a problem. Did you enter an email address?

; } else { Continued
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

312 Part II . PHP and MySQL Basic (My space web page)

March 22nd, 2008

312 Part II . PHP and MySQL Basic Form Submission to a Database Submitting data to a database via an HTML form is straightforward if the form and formhandler are two separate pages. Listing 17-1, newsletter_signup.html, is a simple form with only one input field. Listing 17-1: A simple form (newsletter_signup.html)

Newsletter sign-up form

Enter your email address and we will send you our weekly newsletter.



Figure 17-1 shows the result of the preceding code sample, a basic form to insert data into a database. You enter the data in the database and acknowledge receipt in the form handler in Listing 17-2, which (with great originality) we are calling formhandler.php.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Building Forms from Queries Form handling is one (Net web server)

March 21st, 2008

Building Forms from Queries Form handling is one of PHP s very 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 supremely useful Web tasks. HTML Forms You already know most of what you need to make good forms to be handled by PHP and a database. There are a few PHP-specific points to brush up on: . Always, always, always use a NAME for every data entry element (INPUT, SELECT, TEXTAREA, and so on). These NAME attributes will become PHP variable names you will not be able to access your values if you do not use a NAME attribute for each one. If your WYSIWYG editor doesn t allow you to do this, you ll need to remember to add these NAME attributes by hand. . A form field NAME does not need to be the same as the corresponding database field name, but it s often a good idea. . You can (and usually should) specify a VALUE rather than let HTML send the default value. Consider substituting a numerical value for a text value if possible, because the database is much slower at matching strings than integers. . The VALUE can be set to data you wish to display in the form. . Remember that you can pass hidden variables from form to form (or page) using the HIDDEN data entry elements. This practice may have negative security implications, but it s often no worse than storing the data in a cookie. . Remember that you can pass multiple variables in an array but you need to inform the user that this is a possibility. See Chapter 7 for more information on how to format an HTML form for use with PHP. Cross- Reference 1C H A7P7T E R . . . . In This Chapter Understanding HTML forms Submitting data via forms Self-submitting forms Editing data with an HTML form . . . .
You want to have a cheap webhost for your apache application, then check apache web hosting services.

Web design conference - Chapter 16 . Displaying Queries in Tables 309

March 21st, 2008

Chapter 16 . Displaying Queries in Tables 309 The only tricky thing in creating these sample tables is setting up the relational structure. We want each city row to have an appropriate countryID, which should be equal to the actual ID of the appropriate row from the country table. However, these countryIDs are automatically assigned in sequence by MySQL and are not under our control. How can we know the right countryID to assign? The answer is in the incredibly handy function mysql_insert_id(), which recovers the ID associated with the last INSERT query made via the given database connection. We insert the new country, recover the ID of the newly created row, and then use that ID in our city insertion queries. Summary Database interaction is one of the areas where PHP really shines. One very common use for database-enabled Web code is simply to display database contents attractively. One approach to this kind of display is to map the contents of database tables, or SELECT statements, to corresponding HTML table elements. When the mapping is simple enough, you can employ reusable functions that take arbitrary table names, or SELECT statements, and display them as a grid. When you need a more complicated combination of information from relational tables, you probably need a specialpurpose function, but certain tricks recur there as well. One such trick is to craft a SQL statement that returns all the information you need, in the order you want, and selectively print only the nonredundant portions. Near the end of this chapter, we saw a quick example of populating a set of database tables using INSERT statements. Aside from that, all the techniques in this chapter were read-only and do not modify the contents of databases at all. In Chapter 17, we ll see how you can get a more intimate connection to your database by combining SQL queries with HTML forms. . . .
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

308 Part (Web site traffic) II . PHP and MySQL Listing

March 20th, 2008

308 Part II . PHP and MySQL Listing 16-5 (continued) } function populate_cities_db($dbh) { /* drop tables if they exist — permits function to be tried more than once */ mysql_query( DROP TABLE city , $dbh); mysql_query( DROP TABLE country , $dbh); /* create the tables */ mysql_query( CREATE TABLE country (ID int not null auto_increment primary key, continent varchar(50), countryname varchar(50)) , $dbh) OR die(mysql_error()); mysql_query( create table city (ID int not null auto_increment primary key, countryID int not null, cityname varchar(50)) , $dbh) OR die(mysql_error()); /* store data in the tables */ add_new_country($dbh, Africa , Kenya , array( Nairobi , Mombasa , Meru )); add_new_country($dbh, South America , Brazil , array( Rio de Janeiro , Sao Paulo , Salvador , Belo Horizonte )); add_new_country($dbh, North America , USA , array( Chicago , New York , Houston , Miami )); add_new_country($dbh, North America , Canada , array( Montreal , Windsor , Winnipeg )); print( Sample database created
); } ?> Creating a sample database You should be able to use this code to recreate the sample database on your development machine, assuming that you have PHP and MySQL configured, and an appropriately located file called phpbook-vars.inc containing username, password, and database-name strings. Just as in the display examples, this code sends off query strings (with embedded variables), but this time the queries are INSERT statements, which create new table rows. For the most part, the data inserted is just string data passed in to the function, although we chose to pass in an arbitrary number of cities per country by using an array.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Chapter 16 . Displaying Queries in Tables 307 (Free php web host)

March 20th, 2008

Chapter 16 . Displaying Queries in Tables 307 This code is somewhat tricky although it goes through the result rows in order, and everything it prints is grabbed from the current row, it prints countries only when their values have changed. (Continents are still printed redundantly.) The change in a country is detected by monitoring the ID field of the country row. A country change is also a signal to print out the HTML necessary to close off the preceding table row and start a new one. Finally, the code must handle printing the HTML necessary to start the first row and end the last one. Creating the Sample Tables Now we will show you the PHP/MySQL code we actually used to create the sample tables. (Such data might more normally be created by interacting only with MySQL, but we decided to respect our book s title by doing it from PHP.) The code (shown in Listing 16-5) is a specialpurpose, one-time hack, not a model of style, but it has useful examples of using the SQL INSERT statement. Listing 16-5: Creating the sample tables If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.

Web site counters - 306 Part II . PHP and MySQL Listing

March 20th, 2008

306 Part II . PHP and MySQL Listing 16-4 (continued) print(

ContinentCountry Cities
$continent$country_name ); /* the new country is no longer new */ $old_country_id = $country_id; } /* the only thing that is printed for every result row is the name of a city */ $city_name = $row_array[3]; print( $city_name
); } /* close off final country and table */ print(
); } ?> Cities by Country
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Chapter 16 . Displaying Queries in Tables 305 (Photo web hosting)

March 19th, 2008

Chapter 16 . Displaying Queries in Tables 305 The strategy is appealingly simple: There is an outer loop that uses one query to proceed through all the countries, saving the country s name and the primary ID field of each country row. Then for each country, the ID field is used to look up all the cities belonging to that country. Notice the trick of embedding the $countryid variable in the inner query the query string sent is actually different on each iteration through the country loop. Simple? Yes. Efficient? Probably not. This code makes a separate city query for each country. If there are 500 countries in the database, this function will make 501 separate database queries (the extra one being the enclosing country query). Your mileage will vary according to how efficient your particular database is in parsing queries and planning query retrieval, but the sum of these queries will certainly take more time than the simple query we started this section with. A complex printing example Now let s solve exactly the same problem, but using a different strategy. Instead of making multiple queries, we will make a single query and print the resulting rows selectively, so that each HTML table row corresponds to more than one database row (see Listing 16-4). The resulting browser display is exactly the same as in the previous example. Listing 16-4: A complex display with a single query \n ); Continued
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.