Combine php and html code

This chapter is from the book

Combining HTML and PHP Code on a Single Page

In some circumstances, you may want to include form-parsing code on the same page as a hard-coded HTML form. Such a combination can be useful if you need to present the same form to the user more than once. You would have more flexibility if you were to write the entire page dynamically, of course, but you would miss out on one of the great strengths of PHP. The more standard HTML you can leave in your pages, the easier they will be for designers and page builders to amend without reference to you. You should avoid scattering substantial chunks of PHP code throughout your documents, however. This will make them hard to read and maintain. Where possible you should create functions that can be called from within your HTML code, and can be reused in other projects.

For the following examples, imagine that we are creating a site that teaches basic math to preschool children and have been asked to create a script that takes a number from form input and tells the user whether it is larger or smaller than a predefined integer.

Listing 9.8 creates the HTML. For this example, we need only a single text field, but even so, we'll include a little PHP.

Listing 9.8 An HTML Form that Calls Itself

 1: 
 2: 
 3: Listing 9.8 An HTML form that calls itself
 4: 
 5: 
 6: 
 7: Type your guess here: 
 8: 
 9: 
10:  

Whatever we name the page that contains this form, the fact that we have left out the action attribute of the form element will mean that the form will be submitted back to its own url.

NOTE

Almost all browsers will submit a form to its current page if the form element's action attribute is omitted. You can, however, explicitly tell the browser to submit a form back to its own document by using the predefined $PHP_SELF variable.

Chủ Đề