
According to Netcraft, PHP overtook Microsoft's ASP as the most popular web scripting language back in the spring of 2002. And PHP has continued its explosive growth ever since. Today, when the Apache web server powers nearly 70% of all sites on the Internet and its closest competitor, Microsoft's IIS, has a market share of just over 20%, PHP is far and away the most widely used server-side scripting language. Just what is it that makes PHP so popular?
PHP Is Free. PHP is free software. It is free in the sense of being free to use as you see fit, and also free in terms of cost. Moreover, PHP is open source — if you have the ability and inclination, you can examine the source code for the PHP interpreter (which is written in C) and even modify it. In fact, PHP is part of an open source "stack" of dynamic web publishing software known as LAMP, which stands for Linux, Apache, MySQL and either PHP, Perl or Python. While Perl and Python are also widely used, PHP is the language most commonly employed with the open source Apache web server and MySQL database. And you're not limited to running Apache-MySQL-PHP on Linux, though this is the most frequent scenario. There are also WAMP (Windows) and DAMP (Darwin, i.e., OS X) configurations.
Because you and/or your hosting provider don't have to pay licensing fees for PHP, Apache or MySQL, chances are you can operate your site less expensively than you could if you used a competing technology. In general, a LAMP site is far more cost-efficient to administer and maintain than any sort of dynamic site on Windows and IIS. I would argue that it's more reliable, too.
PHP Is Cross-Platform and Portable. As noted above, PHP (and Apache and MySQL) can run on almost anything. So if you develop with PHP, you have the benefit of unprecedented portability. For example, you can write your web applications on a Windows or OS X box and host on Linux. If for some reason you decide to move your PHP site to a Windows or OS X server down the road, you can do that without the need to change your code. This portability represents yet another kind of freedom you don't get with competing technologies.
PHP is generally used with the Apache web server, but it will also work with IIS or any other web server that supports the CGI standard. Similarly, PHP is commonly used with the MySQL database, but it also works just fine with PostgreSQL, Oracle, Microsoft SQL Server and many others.
PHP Was Built for the Web. PHP was created from the ground up as a web programming language. Many tasks — such as accessing form submissions and talking to a database — are easier in PHP as a result. And PHP scales well: its more complex capabilities such as object-oriented programming, XML processing and dynamic image generation are there when you need them, but stay out of the way when you don't. So in the beginning, while you're learning to use PHP, you can concentrate on the basics of handling user input and displaying output.
To start learning PHP, your first step should be to install it. While detailed installation instructions are beyond the scope of this article, such instructions are not hard to come by — there are a number of articles here at CMX that detail the process, and some of these articles are free.
I recommend you install PHP 5. Although PHP 4 is still more widespread among hosting providers, this will gradually change; you may as well learn PHP using the latest version. The practice code you'll be writing should work in either version (I'll let you know if it doesn't). I also recommend you install the Apache web server, regardless of which platform you develop on, and install PHP as an Apache module (rather than installing the CGI version). Both the Apache and PHP sites offer additional installation instructions. Finally, you need to install MySQL. Again, you should find plenty of documentation on the MySQL site.
I think you'll find a couple of good books to be indispensable in learning PHP as well, so I'll recommend some here. PHP and MySQL Web Development, by Luke Welling and Laura Thomson (Sams, 3rd Edition, 2004) is excellent. The original 2001 edition served as my introduction to PHP; this new 3rd edition has coverage of both PHP 5 and the forthcoming MySQL 5. Learning PHP 5 by David Sklar (O'Reilly, 2004) is also very good, and quite accessible. Both books are available from Amazon and elsewhere, and both books have detailed installation instructions.
The best way to begin is to begin. Rather than starting with a litany of syntax and usage conventions, as "newbie" articles frequently do, let's jump right in and do a little programming in PHP. We'll examine the code and pick up some syntax and usage tips along the way. I'll then go on to provide a more complete sampling of usage do's, don'ts and how-tos. Finally, we'll wrap up Part 1 by connecting to, and displaying data from, a MySQL database.
The code below is a variant on the traditional "Hello, World!" beginner's programming exercise. But rather than using PHP to write a static greeting on your web page, let's add a little interest by calling on PHP's dynamic capabilities. We'll do this by capturing the contents of a user-submitted form, then "printing" those contents to the page.
Here is the code:
<html>
<head>
<title>Hi <?php print $_POST['x']; ?></title>
</head>
<body><br><br>
<div align="center">
<?php
//Print a greeting if the form was submitted
if ($_POST['x']) {
print "Hi, ";
//Print what was submitted in the form
print $_POST['x'];
print "!";
} else {
print "<form method=\"post\"
action=\"$_SERVER[PHP_SELF]\">";
print "Your Name: <input type=\"text\"
name=\"x\">";
print " ";
print "<input type=\"submit\" value=\"Say Hi\">";
print "</form>";
} ?>
</div>
</body>
</html>
Save this code as say_hello.php (or something similar) in your web server's root directory. Then launch a browser and direct it to http://localhost/say_hello.php. You should see this:

Figure 1 The "Say Hi" Form
When the user enters something into the text field and clicks Say Hi, PHP captures the form data and "prints" it to the web page, like so:

Figure 2 The form results
It's worth noting that this is the same web page we began with — PHP has simply changed the page contents to reflect the changed circumstances, as determined by the little program we wrote. Let's take a quick walk through the code to see how it works.
We've placed a PHP statement within the HTML <title> tags. The PHP interpreter processes the code between <?php (the PHP start tag) and ?> (the PHP end tag). In this case, we're instructing PHP to print, or write out/display, the value of the submitted form parameter x ("Tom" in the example above).
Further down on the page is another block of PHP code. It incorporates an if statement to test whether or not the browser has returned the form parameter x. If the browser has in fact done this, PHP performs a specific action. If the browser has not returned the form parameter, PHP performs a different action.
Let's say the browser has returned the form parameter. In that case, PHP prints a greeting using the value of the submitted parameter (e.g., "Hi, Tom!"). Note that we've called this out with a comment, using the // notation. (Everything from // to the end of the line is a comment, and is ignored by PHP.) Also note that PHP's instructions are contained within curly braces ({}), and that each line of PHP code is concluded with a semicolon (;):
if ($_POST['x']) {
print "Hi, ";
//Print what was submitted in the form
print $_POST['x'];
print "!";
}
If, on the other hand, the browser has not returned the form parameter, then condition number two kicks in: the else eventuality. PHP either does this, or else it does that (in this example, anyway). The else clause contains a second set of curly braces with PHP's alternative instructions:
else {
print "<form method=\"post\"
action=\"$_SERVER[PHP_SELF]\">";
print "Your Name: <input type=\"text\"
name=\"x\">";
print " ";
print "<input type=\"submit\" value=\"Say Hi\">";
print "</form>";
}
What we're saying here is, if the browser has not returned the form parameter, then PHP is to print (i.e., display) the actual form. As you can see, the code writes out the form on separate lines; each print statement is enclosed within quotation marks and concluded with a semicolon. The backward slashes are necessary to escape the quotation marks within the statements. $_SERVER[PHP_SELF] is a special PHP variable (all variables begin with $, by the way) that contains the URL of the current page. So by setting $_SERVER[PHP_SELF] as the form action, we can show the form and display its results on the same page. When you first visit say_hello.php, you'll see the actual form, as shown in Figure 1. After you enter some information into the form and submit it, you'll see a page similar to that shown in Figure 2.
There are some fundamental formatting and usage issues you need to keep in mind. One concerns the PHP start tag. You may see <? used as a PHP start tag at times (instead of <?php). It is not a good idea to use this short form, however, since it can be turned on or off with a PHP configuration setting. The <?php start tag, on the other hand, will work on any server running the PHP interpreter.
PHP ignores whitespace (i.e., spaces, tabs and newlines). That means it's up to you to code in a logical, readable style without excess white space. In general, it's good programming practice to put one statement on a line, and add blank lines only if absolutely necessary for readability.
PHP is also case-insensitive in many areas. Keywords (such as print) and function names are not case-sensitive. Again, it is your responsibility to code in a logical, readable and consistent style. I personally prefer lowercase except when conventional usage ($_SERVER[PHP_SELF], for example) dictates otherwise. Variables, it should be noted, are case-sensitive. $user is not the same as $USER.
As you saw in our coding example, beginning a line with // is one way to add a comment to your code. This method of commenting is also used in C++, Java, JavaScript and ActionScript. PHP also supports Perl-style single-line comments beginning with #.
Multiline comments begin with /* and conclude with */. Using multiline comments can be a useful way to temporarily turn off a block of code during testing.
MySQL is the world's most popular open source database. It's noted for raw speed, and for being an ideal programming partner for PHP. The combination of PHP's power and ease-of-use, together with MySQL's speed, is ideal for web development. And both PHP and MySQL grow more powerful with each new release.
For our next exercise, let's begin by creating a new database in your MySQL installation — we'll call this database programming. Because we're focusing on PHP here, I will assume that you've done the reading necessary for understanding how to access and operate MySQL at a basic level. The documentation on the MySQL site should help, and so should this article.
Begin by typing this at your mysql> prompt:
create database programming;
Next, we will create a table called languages to insert into our new programming database. Before we do that, we'll need to tell MySQL that this new table targets the programming database. Type use programming; at the mysql> prompt and press Enter or Return. You should see the message "Database changed" and be returned to the prompt. To create the table structure for the new languages table, type the following at the mysql> prompt:
create table languages (
language_id int unsigned not null auto_increment
primary key,
name varchar(10),
platform varchar(10)
);
TIP: unsigned simply means that the integer type can only have a zero or positive value.
After you press Enter, you should see "Query OK, 0 rows affected" and be returned to the mysql> prompt. To verify that the table structure was created successfully, type describe languages; at the prompt. You should see something like this:

Figure 3 Viewing a MySQL table from the command
line
Now we need to get some data into our table. Type the following lines at the mysql> prompt, pressing Enter after each:
INSERT INTO languages VALUES (1, '.NET', 'Windows');
INSERT INTO languages VALUES (2, 'ColdFusion', 'Windows');
INSERT INTO languages VALUES (3, 'PHP', 'Linux');
After you enter each line, you should see the message "Query OK, 1 row affected". To make sure we entered the data successfully, type this command at the mysql> prompt:
SELECT * FROM languages;
You should see something like this:

Figure 4 Retrieving table data with a SQL
SELECT statement
OK, we've created a new programming database and populated a languages table within it. Now it's time to connect to the database with PHP.
There are a number of ways to connect to your database using PHP. For this introductory exercise, we will use one of the most common, the mysql_pconnect() function. The p in mysql_pconnect() stands for persistent — this function, unlike the similar mysql_connect(), returns a persistent connection to the database that remains open after the script finishes executing. If you are going to make persistent calls to your MySQL database, using mysql_pconnect can save time and server overhead.
Let's create a simple PHP page that connects to and queries our new programming database, then displays the table data. Here is the code:
<html>
<head>
<title>Sample Connection</title>
</head>
<body><br><br>
<div align="center">
<?php
$db = mysql_pconnect("localhost", "root",
"password");
if (!db)
{
print "Error: Could not connect to database.";
exit;
}
mysql_select_db("programming");
$query = "select * from languages order by name
asc";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
print "Today's web developers should be familiar
with<br><br>";
for ($i=0; $i<$num_results; $i++) {
$row = mysql_fetch_array($result);
print ($row["name"]);
print " on ";
print ($row["platform"]);
print "<br>";
}
?>
</div>
</body>
</html>
The code above assumes you are using your MySQL root account on localhost, and that you've assigned a password to the MySQL root account. (You'll need to use your actual password in place of "password" above.)
If you've got everything working properly, the page should look like this:

Figure 5 Connecting to and Displaying Data
from a MySQL Database
Here's a quick run-through of the entire page. We begin by using the mysql_pconnect function to connect to our database, passing the host name, username and password to mysql_pconnect. Next, we use an if statement to test whether the connection was made. If no connection exists (!db), we would print an error message and exit the program.
However, if we make a successful connection, we then use the mysql_select_db function to choose the database we want to use ("programming"). Following that, we specify a query on the database which selects everything from the languages table and sorts it in ascending order by the name column (i.e., in alphabetical order). We then run the query ($result = mysql_query($query);), using the mysql_query() function and passing the $query string as a parameter.
We have a number of functions available to access the results of the query. For example, the function mysql_numrows() provides the number of rows returned by the query. We have passed it the $result variable, like so:
$num_results = mysql_num_rows($result);
This enables us to loop through the results:
for ($i=0; $i <$num_results; $i++)
Each iteration of the loop calls the mysql_fetch_array() function, which takes each row from the recordset and returns it as an associative array, with each key an attribute name and each value the corresponding value in the array:
$row = mysql_fetch_array($result);
There are several variations on this, which I won't confuse you with now. The important thing is that you grasp the basic concepts involved here.
If you don't completely understand everything in this article, don't worry — it is meant as an introduction, after all, and we've covered a fair amount of ground. But it is important that you practice the exercises given here until you do understand them, and can make them work. This will give you a good foundation for further explorations of PHP and MySQL, which we'll undertake in Part 2.
Approximate download size: 219k
Keywords
PHP, PHP 5, MySQL