PHP and HTML controls
Unit: 14 of 18
Through the previous examples in this course we have already used HTML several times to influence the formatting of the output (structure) of our application. First, I worked with the most basic tags (say, most often it was the <br> tag for a new line).
Given that, in fact, all HTML is plain text, it is clear that implementing PHP in HTML code involves passing specially formatted textual content to the output. Practically speaking: how that content will be structured and how it will look, we solve with HTML (and later with CSS), and how it will work – we solve with PHP.
Dynamics in HTML
PHP in HTML can be implemented in several ways, depending on the programmer’s style and needs (sometimes we make the decision ourselves, and sometimes we are forced to use one of the styles depending on how our code is left).
For example, in the first case, we can output HTML from PHP:
1
2
3
4
5
|
<?php echo "<strong>test</strong>" ; ?> |
In the second case, we can include PHP in HTML:
1
2
3
4
5
6
7
8
9
|
<strong> <?php echo "test" ; ?> </strong> |
Although they are diametrically different in appearance, these two codes will give exactly the same result in the browser, which for the user is the most important thing – not to feel the difference in the use of the code, or at least not to feel that there was a damage.
This means that when we generate an HTML page, it is not important how we get the result, only what that result will look like. Our recommendation is, of course, to always stick to one type and way of dynamically generating HTML – this will give you consistency, make your code easier to manage, and probably make more and more code work and call it again instead of repeating it.
From these it follows that we can generate fully dynamic control. For example, let’s take a text box control, for which, before we get to some data, we can’t be sure what the value in the text box will be:
1
|
<input type= "text" value= "unknown value" /> |
Using PHP, it is possible to populate this control with data. It is only important that in some part of the code, before drawing the control, we get the desired data. In this case, at the beginning of the code we assigned the value “trial/test” to the variable $x. The PHP tag is closed, and there can be an unlimited amount of HTML code between this tag and the text box control. Finally, when the control is drawn, we will insert the PHP tag into the value field and then execute the output of the desired content. Since everything is processed by the interpreter within the PHP tags, the output of this code will only be reduced to what we want to output. In this case, the string “sample/test” will be written in the text box.
1
2
3
4
|
<?php $x = "test" ; ?> <input type= "text" value= "<?php echo $x; ?>" /> |
We could, of course, have put much more complex logic into the control itself:
1
2
3
4
5
6
7
|
<input type= "text" value="<?php //no matter how much code does our php section contain //HTML will only show the parts that where explicitly echoed //from PHP $x = "proba" ; echo $x ; ?>" /> |
Of course, it is not recommended to make the code unreadable like this, i.e. to put the code like this in an attribute of the HTML element, where the formatting becomes very hard to follow.
Now the question arises as to the purpose of drawing this text box, and as a better solution, we impose the function that will do this at our request.
First, let’s create a function that draws the control:
1
2
3
4
5
6
|
<?php function box() { echo "<input name=\"\" type=\"text\" value=\"test\">" ; } ?> |
…then call this control anywhere in the code:
1
2
3
4
5
|
<form id= "form1" name= "form1" method= "post" action= "" > <?php box(); ?> </form> |
Now we have an almost completely dynamic control in the HTML document. Almost completely, because this control can’t do anything, because it has no identifier . Its content cannot be accepted by standard methods of sending values over HTTP.
But if we make a small change and parametrize the box() function in such a way that its parameters accept the attributes we want to name
1
2
3
4
5
6
|
<?php function box( $name , $value ) { echo "<input name=\"$name\" type=\"text\" value=\"$value\">" ; } ?> |
we get a control that we can initialize in a simple, transparent and fast way. If we put this type of control in a separate file (for example, kontrolle.php.inc), we will only be able to change the full application-wide controls in a function.
The whole philosophy of dynamics in the PHP programming language (generally speaking) is basically explained by this. If this philosophy should be reduced to its essence, then we can state it like this:
- code simplification (easier code maintenance, we generally define it in one place, call it in more places);
- enabling the use of data from other sources, such as the database (does not have to be enclosed in files);
- enabling flow control (we can ask something and, depending on the answer, change the code);
- generating code by code (in this case, for example, we dynamically generated HTML via PHP).
In the next lessons, we’ll learn how to use the form to take the data from the control and process it further, thus rounding this integer.
HTML data and controls
To get some data, we need a source. So far, we have familiarized ourselves with databases, which are the most common data source for web applications. XML files and JSON files can also be (and often are at least part of) the data source. For our current needs, to keep things as simple as possible, we won’t use them, but instead create a string with a few members by hand:
1
2
3
4
5
|
<?php $places = array ( "serbia" => "belgrade" , "france" => "paris" , "england" => "london" , "spain" => "madrid" , "germany" => "berlin" ); ?> |
For example, we want to place the contents of this string into a specific option box:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<select> <?php foreach ( $places as $state => $city ) { ?> <option value= "<?php echo $state; ?>" ><?php echo $ state; ?></option> <?php } ?> </select> |
We notice that the PHP tag can be cut off by the HTML at any time and then resumed at some point, and the process (in this case the foreach loop) will still be active. We had to close the loop, otherwise PHP would have thrown an error.
In this example, we also see how to populate the option box with data. It should be known that in the process of sending data, the current value will be considered the value in the field value (cities), and if it does not exist, the current value will be the value of the element (country).
To set the selection to a specific field value (for example, we want to set to Paris – France), we need to add more PHP code to the option tag and change it to look like this:
1
|
<option <?php if ( $city == "paris" ) { ?> selected= "selected" <?php } ?> value= "<?php echo $city; ?>" ><?php echo $state ; ?></option> |
Given that the option element of the option box (select) control has a selected attribute, which, if its value is “selected”, sets the selection to that element, we only check during the loop if, among other things, the current member of the string is the that we want to be selected. If that member is a string, with the PHP command we actually print the attribute and assign it the desired value.
If we put all of this in a function, we’d get cleaner code and improved functionality:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<?php function option( $places , $selection ) { echo "<select>" ; foreach ( $places as $state => $city ) { echo "<option " ; if ( $city == $selection ) echo "selected=\"selected\"" ; echo "value=\"" . $city . "\">" ; echo $state . "</option>" ; } echo "</select>" ; } ?> |
Now we can pass any string of pairs to this function anywhere in the code, even the capital of the country we want it to be selected for:
1
2
3
4
5
6
7
|
<?php $places = array ( "serbia" => "belgrade" , "france" => "paris" , "england" => "london" , "spain" => "madrid" , "germany" => "berlin" ); option( $places , "madrid" ); ?> |
In addition, we can easily create an unlimited number of such controls, each with a different set of data. For example, if we had a two-dimensional array:
1
2
3
4
5
6
7
8
9
|
<?php $places = array ( "serbia" => "belgrade" , "france" => "paris" , "england" => "london" , "spain" => "madrid" , "germany" => "berlin" ), array ( "zastava" => "yugo" , "peugeot" => " 406" , "ford" => "taurus" , "seat" => "ibiza" , "bmw" => "353" ), ); ?> |
We could easily create controls for substrings in two lines of code:
1
2
3
4
5
6
7
|
<?php foreach ( $arrays as $places ) option( $places , "" ); ?> |
If you try to copy the substrings of $strings multiple times and start the program again, you will see that the number of checks will increase.
These controls, in this form, are unusable for submitting data because they have no identifiers and are not enclosed in the form. You can easily solve this by adding one more parameter to the option() function, where you will also dynamically pass the identifiers for the controls.
You also don’t have to use double quotes when creating HTML controls with the echo command. You can use single quotes instead, where you won’t need to enter the escape character before each quote that should be treated as a string (\).
We have practically seen on the example that not much has changed: we have the HTMLControls class and the option method in it, the result of which is completely identical to the option function . We also see that the option method receives parameters in an identical way.
In a similar way, we can also create our own grid control:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<?php $places = array ( "serbia" => "belgrade" , "france" => "paris" , "england" => "london" , "spain" => "madrid" , "germany" => "berlin" ); ?> <table width= "100%" height= "10" border= "0" cellpadding= "0" cellspacing= "0" > <?php $counter =0; foreach ( $places as $state => $city ) { ?> <tr <?php if ( $counter %2==0) echo "style=\"background-color:#D7F7FF;\"" ; else echo "style=\"background-color:#9BD7FF;\"" ; ?>> <td valign= "top" ><?php echo $state ; ?></td> <td valign= "top" ><?php echo $city ; ?></td> </tr> <?php $counter ++; } ?> </table> |
To draw, here we use the rows of the table. (This is not a very popular approach, working with DIV tags is recommended instead of tables, but is used here for a simpler example setting). After initializing the string (which we’ve done in all the examples so far), we start drawing the table. The table won’t loop, so we place the PHP block inside it. What we want to repeat in the table are the rows. That’s why we put in each round of the loop one row (tr) and in it, two columns. Before the loop, we set a counter, with which we will check whether the row is even or odd, and based on this it emits a certain color. In columns (td) we place the current data in the loop.
The coding techniques we covered in this lesson are fairly simple for smaller examples, but are very difficult to manage when larger amounts of code are involved. That’s why it’s becoming more and more important to separate HTML and PHP code into separate entities. Most often, this choice comes down to the taste and capabilities of the programmer.
The elaborate technique of writing HTML and PHP code in the same document is also called inline coding or spaghetti code , and the aforementioned separation of HTML and PHP code into separate units – code behind .
Contrary to what we have seen, the main idea is that we write the complete PHP code in separate files, and in the places where the HTML is, we call functions or methods (depending on the programming approach) and just execute them. This way it is much easier to maintain the code because we know exactly where our dynamic logic (PHP) is and where our HTML is. Also, this way of working is recognized by the MVC framework, where the model includes working with the database, processing data and preparing it for printing, and the printing itself is done in the view, which is nothing but HTML in which we call the model as needed.
Provided that there are $value and $name variables in the preceding code, the line echo\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”; will:
Exercise 14.01
Create a Form class.
In the constructor of this form you receive the parameters for the form method (GET or POST) and for the form action (where it will lead us).
Format the beginning of the HTML form based on these parameters and store it in a field in the class.
Next, create a method that will add input element types.
This method can receive the input type of the name field and if the field is required and if it has a predefined value.
Using concatenation, format this field and add it to the field we already formatted and saved the beginning of the form element.
In addition to this, it is also necessary to create a method for adding a label that will receive a value for the for attribute and a value for print.
In the same way, add the created label to the field where the rest of the defined HTML is located.
It is also necessary to create methods for select element and option element, texting element.
Finally, also create a method that will populate the form element and return its value on output.
Instantiate this class and create a form.
Note:
You can view an example of the solution to this exercise in the repository of this course or at the following link: |