Ready for your first taste of PHP? This section contains a few program listings and explanations of what they do. If you don’t understand everything going on in each listing, don’t worry! That’s what the rest of the book is for. Read these listings to get a sense of what PHP programs look like and an outline of how they work. Don’t sweat the details yet.
When given a program to run, the PHP engine pays attention only to the parts of the program between PHP start and end tags. Whatever’s outside those tags is printed with no modification. This makes it easy to embed small bits of PHP in pages that mostly contain HTML. The PHP engine runs the commands between <?php (the PHP start tag) and ?> (the PHP end tag). PHP pages typically live in files whose names end in .php. Example 1-1 shows a page with one PHP command.
Example 1-1. Hello, World!
<html>
<head><title>PHP says hello</title></head>
<body>
<b>
<?php
print “Hello, World!“;
?>
</b>
</body>
</html>
The output of Example 1-1 is:
<html>
<head><title>PHP says hello</title></head> <body>
<b>
Hello, World!</b>
</body>
</html>
In your web browser, this looks like Figure 1-3
Printing a message that never changes is not a very exciting use of PHP, however. You could have included the “Hello, World!” message in a plain HTML page with the same result. More useful is printing dynamic data—i.e., information that changes. One of the most common sources of information for PHP programs is the user: the browser displays a form, the user enters information into that and hits the “submit” button, the browser sends that information to the server, and the server finally passes it on to the PHP engine where it is available to your program.
Example 1-2 is an HTML form with no PHP. The form consists simply of a text box named user and a Submit button. The form submits to sayhello.php, specified via the <form> tag’s action attribute.
Example 1-2. HTML form for submitting data
<form method=“POST” action=“sayhello.php”>
Your Name: <input type=“text” name=“user” />
<br/>
<button type=“submit””>Say Hello</button>
</form>
Your web browser renders the HTML in Example 1-2 into the form shown in Figure 1-4.
Example 1-3 shows the sayhello.php program that prints a greeting to whomever is named in the form’s text box.
Example 1-3. Dynamic data
<?php
print “Hello, “;
// Print what was submitted in the form parameter called ‘user’
print $_POST[‘user’];
print “!”;
?>
If you type Ellen in the text box and submit the form, then Example 1-3 prints Hello, Ellen!. Figure 1-5 shows how your web browser displays that.
$_POST holds the values of submitted form parameters. In programming terminology, it is a variable, so called because you can change the values it holds. In particular, it is an array variable, because it can hold more than one value. This particular array is discussed in Chapter 7. Arrays in general are discussed in Chapter 4.
In this example, the line that begins with // is called a comment line. Comment lines are there for human readers of source code and are ignored by the PHP engine. Comments are useful for annotating your programs with information about how they work. “Comments” on page 15 discusses comments in more detail.
You can also use PHP to print out the HTML form that lets someone submit a value for user. This is shown in Example 1-4.
Example 1-4. Printing a form
<?php
print <<<_HTML_
form method=”post” action=”$_SERVER[PHP_SELF]”>
Your Name: <input type=”text” name=”user” /> <br/>
<button type=”submit”>Say Hetto</button>
</form>
_HTML_;
?>
Example 1-4 uses a string syntax called a here document. Everything between the <<<_HTML_ and the _HTML_ is passed to the print command to be displayed. Just like in Example 1-3, a variable inside the string is replaced with its value. This time, the variable is $_SERVER[PHP_SELF]. This is a special PHP variable that contains the URL (without the protocol or hostname) of the current page. If the URL for the page in Example 1-4 is http://www.example.com/users/enter.php, then $_SERVER[PHP_SELF] contains /users/enter.php.
With $_SERVER[PHP_SELF] as the form action, you can put the code for printing a form and for doing something with the submitted form data in the same page. Example 1-5 combines Examples 1-3 and 1-4 into one page that displays a form and prints a greeting when the form is submitted.
Example 1-5. Printing a greeting or a form
<?php
// Print a greeting if the form was submitted
if ($_POST[‘user’]) {
print “Hello, “;
// Print what was submitted in the form parameter called ‘user’
print $_POST[‘user’];
print “!”;
} else {
// Otherwise, print the form
print <<<_HTML_
<form method=”post” action=”$_SERVER[PHP_SELF]”>
Your Name: <input type=”text” name=”user” />
<br/>
<button type=”submit”>Say Hello</button>
</form>
_HTML_;
}
?>
Example 1-5 uses the if() construct to see whether the browser sent a value for the form parameter user. It uses that to decide which of two things to do: print a greeting or print a form. Chapter 3 talks about if(). Using $_SERVER[PHP_SELF] and processing forms are discussed in Chapter 7.
PHP has a huge library of internal functions that you can use in your programs. These functions help you accomplish common tasks. One built-in function is number_format(), which provides a formatted version of a number. Example 1-6 uses number_format() to print out a number.
Example 1-6. Printing a formatted number
<?php print “The population of the US is about: “;
print number_format( 20853904);
?>
Example 1-6 prints:
The population of the US is about: 320,853,904
Chapter 5 is about functions. It shows you how to write your own and explains the syntax for calling and handling the results of functions. Many functions, includ-ing number_format(), have a return value. This is the result of running the function. In Example 1-6, the data the second print statement is given to print is the return value from number_format(). In this case, it’s the comma-formatted population number.
One of the most common types of programs written in PHP is one that displays a web page containing information retrieved from a database. When you let submitted form parameters control what is pulled from the database, you open the door to a universe of interactivity on your website. Example 1-7 shows a PHP program that connects to a database server, retrieves a list of dishes and their prices based on the value of the form parameter meal, and prints those dishes and prices in an HTML table.
Example 1-7. Displaying information from a database
<?php
// Use the SQLite database ‘dinner.db’
$db = new PDO(‘sqlite:dinner.db’);
// Define what the allowable meals are
$meals = array(‘breakfast’,’lunch’,’dinner’);
// Check if submitted form parameter “‘meal” is one of
// “breakfast”, “lunch”, or “dinner”
if (in_array($_POST[‘meal’], $meals)) {
// If so, get all of the dishes for the specified meal
$stmt = $db->prepare(‘SELECT dish,price FROM meals WHERE meal LIKE ?’);
$stmt->execute(array($_POST[‘meal’]));
$rows = $stmt->fetchAll();
// If no dishes were found in the database, say so
if (count($rows) == 0) {
print “No dishes available.”;
} else {
// Print out each dish and its price as a row
// in an HTML table
print ‘<table><tr><th>Dish</th><th>Price</th></tr>’;
foreach ($rows as $row) {
print “<tr><td>$row[0]</td><td>$row[1]</td></tr>”;
}
print “</table>”;
}
} else {
// This message prints if the submitted parameter “‘meal” isn’t
// “breakfast”, “lunch”, or “‘dinner”
print “Unknown meal.”;
}
?>
There’s a lot going on in Example 1-7, but it’s a testament to the simplicity and power of PHP that it takes only about 20 lines of code (without comments) to make this dynamic, database-backed web page. The following describes what happens in those 20 lines.
The new PDO() function at the top of the example sets up the connection to the SQLite database in a particular file. These functions, like the other database functions used in this example (prepare(), execute(), and fetchAll()), are explained in more detail in Chapter 8.
Things in the program that begin with a $, such as $db, $_POST, $stmt, and $row, are variables. Variables hold values that may change as the program runs or that are created at one point in the program and are saved to use later. Chapter 2 talks about variables.
After connecting to the database, the next task is to see what meal the user requested. The $meals array is initialized to hold the allowable meals: breakfast, lunch, and dinner. The statement in_array($POST[‘ meal’ ], $meals) checks whether the submitted form parameter meal (the value of $_POST[‘meal’]) is in the $meals array. If not, execution skips down to the end of the example, after the last else, and the program prints Unknown meal.
If an acceptable meal was submitted, prepare() and execute() send a query to the database. For example, if the meal is breakfast, the query that is sent is as follows:
SELECT dish,price FROM meals WHERE meal LIKE ‘breakfast’
Queries to SQLite and most other relational databases are written in a language called Structured Query Language (SQL). Chapter 8 provides the basics of SQL. The prepare() function returns an identifier that we can use to get further information about the query.
The fetchAll() function uses that identifier to get all the matching meals the query found in the database. If there are no applicable meals, the program prints No dishes available. Otherwise, it displays information about the matching meals.
The program prints the beginning of the HTML table. Then, it uses the foreach construct to process each dish that the query found. The print statement uses elements of the array returned by fetchAll() to display one table row per dish.
Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.