PHP 101

Tutorial: PHP 101

Introduction

php

PHP, or the PHP Hypertext Processor, has emerged as the most widely used server-side web programming language in use today. PHP makes it easy for web pages to interact with databases, present different kinds of content to different users, manipulate text, send email, process forms, perform advanced mathematics, or do most anything else that involves delivering dynamic data into web pages.

Note: When we say “dynamic,” we’re not talking about animations or whiz-bang graphics — PHP is just for altering and controlling the data that goes into a web page – primarily text. For whiz-bang “client-side” animations, you’ll need Flash or JavaScript.

Literally tens of thousands of software applications living on web servers around the world – from blogging engines to banking systems, bulletin boards to social networks like Facebook – are written in PHP. But PHP isn’t just for big software projects – it’s also an excellent little Swiss Army Knife for small, custom, or one-off jobs on ordinary web sites. Because it’s relatively easy to learn, popular content management systems such as WordPress and Drupal have become enormously popular.

PHP’s success comes from two main factors: Ubuiquity and ease of use.

Ubiquity: Because PHP comes bundled with the Apache web server, and because Apache is the most popular web server software in use, PHP is widely available. Even web servers that don’t run Apache often run PHP, since it’s been ported to run on other servers as well. As a result, virtually every commercial web hosting account comes with PHP pre-installed and ready to run. Developers don’t need to install or configure a thing to get started.

Ease of use: PHP has a very low barrier to entry. As you’ll discover in a moment, a web developer with existing HTML and CSS skills can literally insert one line of code into an existing HTML document, rename the file extension, and have a working PHP document. The developer can then simply build on that base one line at a time, acquiring knowledge as she goes. This is in stark contrast to the learning curve for languages such as Java, or full-blown frameworks like Django or Rails.

Because there are tens of thousands of PHP developers out there, it’s very easy to find answers to PHP questions. Blog posts, forums, and documentation abounds. You’re never far away from a helpful community of programmers ready to help out (as long as you’ve tried to help yourself first!)

This is a “101” tutorial, and is by no means exhaustive – it provides just enough information to get familiar with the basic concepts of server-side programming.

Hello world

Let’s dive in. You’ll need:

  • A web host that supports PHP (most do)
  • S/FTP access to your host (see our FTP Made Simple tutorial)
  • A plain text or programmer’s editor. See the What You Need section of our HTML 101 tutorial for recommendations
  • Basic knowledge of HTML

From this point on, we’ll assume that you know how to upload documents to a directory (folder) on your web host, how to use your text editor, and have basic competency in HTML.

PHP is a server-side programming language, which means that all of the code you write will be interpreted on the server, not in the user’s browser (in contrast to a client-side language like Javascript, which works the other way around). That means it will never be possible for the reader of your site to see a scrap of the PHP code you write – it remains completely hidden from the viewer, even when they “View source” in the browser.

The basic process works like this:

  1. Start with a simple HTML document
  2. Name the document with a .php extension instead of .html
  3. Upload it to a location on the web and visit that URL
  4. Add some PHP code to the document, re-upload, and refresh the browser

Remember: Because PHP is a server-side programming language, you can’t simply save a .php document to your desktop, open it up in a browser, and expect to see anything meaningful. You must place all of the exercises in this tutorial on a real web server and view them over the web.

Tip: If you really want to do PHP development on your desktop, it’s possible to install a real web server on your personal computer. If you’re a Mac user, note that Mac OS comes with Apache and PHP already installed – you just need to configure it. If you’re a Windows user, you can install WAMP to get Apache, PHP, and MySQL database working under Windows.

For the rest of this tutorial, we’ll assume you’re placing your files on a real web host via S/FTP. Let’s start with this simple XHTML document:

Even though there’s no PHP code in it, save that code to a file called hello.php and upload it to your web server, in a folder called phptest. Now find the URL in a browser. It should be something like http://example.com/phptest/hello.php (adjust to match your domain and path).

Now let’s add some PHP to the document. PHP is simply interleaved with existing HTML code wherever necessary, using PHP opening and closing markers, like this:

So let’s introduce the classic “Hello world!” code into our document.

Save and upload the document, overwriting the hello.php file on the server, then click Refresh in your browser. Kind of underwhelming, wasn’t it? That’s OK – we’re just getting our sea legs. The important thing right now is to understand how you were able to switch out of HTML mode, into PHP mode, and back into HTML mode, all in the middle of the same document. You’ll be doing lots of that.

The line between the opening and closing PHP tags is called a “statement,” which is the smallest standalone element of a programming language. Simply put, a statement does a unit of work (in this case, “echoing” something back to the screen.) In PHP, statements always end with a semi-colon — without it, your code will not work, and you’ll get a nasty error message back from the server.

We’ll come back to the date() line later in the tutorial. For now, the objective is to understand how PHP code can be interleaved with HTML.

Note: This tutorial shows and explains example code, but does not show the output of that code. You’ll need to put each sample in a PHP file on a web server to see its output. There’s no better way to learn than to work with actual code yourself.

Commenting your code

All programming languages let you add “comments” to code – sections of text that are meant to be read by the programmer but ignored by the interpreter. Adding comments to code may seem silly when you’re working with “Hello world!,” but it becomes essential when your codebase becomes large and complex – especially if multiple people are working on it. Plan to comment your code any time its purpose isn’t 100% obvious. In PHP, comments can take two forms:

So far so good – you’ve got a working PHP document! Let’s liven things up a bit with dynamic data.

Variables

Now you’ve got a basic PHP document set up, but it doesn’t do anything interesting. You could have just put “Hello World!” directly in HTML. Let’s try something else.

In this example, $yourname is a “variable” – a placeholder unit that can store all kinds of information. The echo statement substitutes the variable placeholder with the value of that variable. In PHP, all variables start with a $ character.

This example still isn’t terribly interesting – you still could have done this in straight HTML. The power of variables becomes clear when you think about all of the places that variable data can come from. $yourname could be pulled from a database after you log into a site. It could be pulled from a parameter in the URL. It could be extracted from a form field submitted by the user on the previous page. It could be pulled from a cookie on the user’s hard drive. The possibilities for interactivity are endless.

So what if you did want to pull $yourname from the URL? Easy. URLs often have a series of “parameters” on the end, with “name/value” pairs like this:

http://example.com/phptest/hello.php?yourname=Joe&yourage=32

The portion after the ? marks the beginning of the parameters, which are separated by & symbols. Ever notice how you can bookmark the URL of a page of Google search results and bring it up later without re-typing your search query? That’s because the search terms are stored as parameters in the URL. This is a very common practice in web development. You can access URL parameters in PHP with the global $_REQUEST variable, which gives you access to information in the browser’s request from the server. Modify your code so it looks like this:

Now refresh the page in the browser. It should read:

Hello Joe! I see that you're 32 years old.

Voila! Instant dynamic web page.

So what’s with the echo(); business we’ve been using? echo() is an example of a “function” – a command that does something to something else. Virtually all programming languages have them. Hundreds of functions come with PHP, and you can use them whenever you need them. You can also write your own functions to perform custom operations. We’ll be doing that later in this tutorial.

A function takes zero or more “arguments,” which tell the function what to act to on and/or how to act on it. In this example, echo() takes a single argument — a string to print back to the screen. “Hello world!” is an argument to the echo() function. We’ll explore functions more thoroughly in a bit – for now, just remember that a pair of parentheses follow a function call, and that arguments to the function go inside the parentheses.

Arrays

We’ve seen how variables can store a single value (which could be a string, or a number, or virtually any type of object). But what happens when you have a lot of variables to keep track of, which are all part of a set? For example, let’s say you performed a query on your database which returned the test scores of all 30 of your students. It would be a major pain to create a new variable for each score. Instead, you’d want to use an “array,” which you can think of sort of like a folder – a single variable storing lots of values.

There are two basic types of arrays in most programming languages. In PHP, the two types are called “indexed” and “associative” arrays. An indexed array is a simple list of values, and it looks like this:

Note that we used a function called “print_r()” here instead of echo(). If you try to “echo” an array back to the screen, you’ll find that you can’t. An array can be gigantic, and can have many “dimensions” (think of folders within folders). So instead, PHP just prints the string “Array()” to the screen. But during testing and development, it’s sometimes useful to force PHP to print out a whole array, and the print_r() function does this for us.

If you want to get at the actual values in an indexed array, you have to refer to them by number. In programming languages, the first element in an array is the 0th, the second element is the 1st, and so on. So try this:

You’ll see the first three elements of the array printed to the screen (without any line breaks, since we didn’t add them, and HTML ignores whitespace). But what if your database query emitted both the names and scores of the students in your class? In that case, you’d want to use an “associative” array, which works more like a phone book, allowing you to look up an array element by name. An associative array looks like this:

That’s more like it! Later we’ll learn how to “iterate” over all elements in an array to print them all out.

If you want to append a new item to the end of an indexed array, simply use:

The new value will be plopped onto the end of the array. If you want to add a value to an associative array, the process is similar, but you need to give the key name at the same time:

Combining Variables

Let’s say you’ve got two strings and you need to combine them into a single string. We’ve seen one example of that already, in our URL parameters example. Here’s another way the same statement could be written:

This example differs from the first one – the argument to echo() is a series of plain text strings and PHP variables, stitched together with periods (dots). The strings are enclosed in quotes and the variables are not. For now, the two methods may seem interchangeable, but as your projects grown in complexity, you’ll find good reasons for using both styles.

It’s also common to build a string entirely in PHP, then spit it back as a single variable, like this:

In this case, we assigned the whole concatenated string to a single variable ($greeting) and passed that as an argument to echo() instead. This technique allows you to build a string slowly as a script progresses, finally spitting back one giant (but neatly contained) variable.

Of course, you’ll often need to insert chunks of HTML into your strings. With PHP, HTML code can be generated like any other string. In this example, we’ll build up our string variable over multiple steps, and insert HTML while we’re at it.

There’s one new concept in that example – notice that we assigned a value to the $greeting variable twice. But the second time, we did it with .= instead of a single = sign. Just like we used the dot operator (period) to concatenate pieces of a string together, we can use .= to concatenate new data onto the end of an existing variable.

Can you guess what would happen if you left the dot out of the second $greeting variable assignment? Try it and see if you were right.

Functions

So far we’ve only been using a single built-in PHP function (echo()), but there are hundreds of them available. Since PHP is built for making web sites, it’s not surprising that it includes a lot of text-manipulation functions. The official PHP documentation lists every single function built into the language, and there’s a whole section on text manipulation functions alone. Let’s try a few, starting with strtoupper(), which simply converts a string to upper case:

You should have gotten back:

MARY HAD A LITTLE LAMB.

There’s a similar strtolower() function which works like you’d expect it to. The basic usage of a function is this:

Most functions take at least one argument (arg1), which is usually the name of the thing you want to do work on, which could be a string, a variable, a number, or whatever is appropriate. Additional arguments (arg2, arg3…) can be used to tell the function how to act. To illustrate that, let’s try out a function that takes more than one argument. The wordwrap() function can occasionally be useful, and takes arguments for width (how wide do you want your text lines to be?) and the line-ending (in this case we’ll insert <br /> tags after each line.)

The script returns:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Tip: The official documentation for each function on php.net can be pretty terse. If you have trouble understanding the abstract function definitions, skip down to the examples section include on each page – it’s usually pretty easy to figure out how to use the function from reading the examples and discussions that follow.

Custom Functions

So far we’ve been working with functions built into PHP itself. Those are essential, but you’ll often need to perform some custom processing on a string, variable, number, or object before you can use it. And you may need to perform that custom processing from many places in your web application. To avoid duplicating code all over the place, you’ll want to wrap up the statements from your custom processing into a function you write yourself, which you can then call from anywhere. Building on our previous examples, let’s say you want to transform a block of text to uppercase and wrap its lines to 20 characters, inserting <br /> tags after each line. Perhaps not very realistic, but useful for our purposes. You’ll need to do two things:

  • Define the function with a name and set of arguments that it takes
  • Call it from elsewhere in your script, supplying the required arguments

In this case, our custom function will take a single argument — a paragraph stored in a variable.

Let’s break it down. On line 2, we define a new function called “convert_string” and specify that it takes a single argument, which will be referred to inside the function as $mystring. Note that this does not mean we have to pass variables called $mystring into the function – the function will take any string variable. $mystring will be what we refer to the passed-in variable as from within the function.

On lines 4 and 5, we use the built-in functions strtoupper() and wordwrap() just as we have in earlier examples. On line 4, we store the result of the strtoupper() as a new variable called $tempstring. On line 5, we pass the new $tempstring variable (which is by this point in all uppercase text) to wordwrap(), overwriting the $tempstring variable. $tempstring is now both wrapped and uppercased.

Line 6 is something new — a “return” statement is how a function creates output. Functions may do hundreds of things while they’re running, but they generally output just one thing. The return statement is how you tell the function what it needs to give back to your program — in this case, the doubly converted string that started as simple paragraph input.

On lines 15 and 17, we declare some simple string variables. These would more likely be paragraphs coming out of a database, but for our purposes, we’re hard-coding them. On lines 20 and 21 we echo them back just so we can compare the originals to the converted versions on the page.

On lines 24 and 25 we put our custom function to work by calling the function by name and passing the raw strings to our function as arguments. Remember, whatever is in the “return” statement of the function will be that function’s output. We nest the call inside an echo() statement here, but we could also have stored it in another variable for further processing.

Custom functions can get much more complex than this of course, but these examples should give you a good sense of how functions work, and how easy it is to write your own.

Experiment: What happens if you call the convert_string() function with no arguments at all? How might you prevent your program from crashing if you were to make that mistake?

Doing Math

There are many cases where it’s useful to perform computations on numbers in PHP. As a journalist, you may need to crunch statistics that come out of a database of health code violations, for example. A school teacher might need to calculate grades by averaging test scores. A shopping site might need to total the value of items in a cart and add appropriate taxes. You might need to compare various numbers to determine the winners of a race, or to see what’s most popular on your site this week. PHP includes a wealth of math-related functions to help you do this.

Here’s a simple example demonstrating how to perform basic calculations:

It’s fairly clear what’s going on here – we assign numeric values to $a and $b, then spit them back twice in our echo() statements – once inside a text string, then again as the result of an equation. We insert some HTML for good measure. Notice that the actual calculations are inside of parentheses – these are needed to tell PHP that you’re performing math in the middle of string output.

Want to get the average of a set of numbers?

Note the placement of the parentheses – you need to establish the logical order of operations just like you did in high school. Of course, that’s a pretty manual method of obtaining an average — we’ve hard-coded in the list of variables and the number “3”. What if we need a script that will average any number of numbers? We’ll come back to that.

Let’s try a more advanced calculation, and experiment with more math functions, by obtaining the value of pi and running it through the round() function to return just three decimal places.

Another common task is to compare two numbers to see if one is larger than the other, or if they’re equal or not equal. PHP includes a set of comparison operators for performing all kinds of comparisons. Comparison operators always return either “true” or “false.” Truth is represented as the number 1, while falsehood is represented by … nothing. Knowing that, try and guess what this script will return:

Was it what you expected? You should have seen a “1,” then a blank line, then another “1.” On line 7, we say “Tell me whether 68 is greater than 14.” It is, so it’s true, and the script returns “1” to represent truth. On line 8, we say “Tell me whether 14 is greater than 68.” It’s not, so the statement is false, so it returns nothing (you get a blank line because of the <br /> tag in the code). On line 9, we say “Tell me whether 68 is equal to 68.” It is, so we get back another “1.”

Notice that we used a double equal sign symbol (==) on line 9. That symbol is used when you’re testing for equality, which is very different from assigning a variable ($a = 9).

This example may seem pretty abstract, but it will make a lot more sense when we get into conditionals in a few minutes (which will let you do things with the results of comparisons like this.)

Datatypes

In the previous sections, we worked with strings that were “in quotes” and numbers that were not. Now you get to find out why.

Different kinds of data are stored in different kinds of variables. A string like “Hello world” is very different from the number 32, which is very different from a binary True/False, which is very different from an array containing multiple variables. These types of variables are called “datatypes.” In PHP, the left side of a variable assignment always looks the same:

$myvar =

It’s what comes on the right side of the “=” sign that distinguishes the datatype. While PHP doesn’t do nearly as much as other programming languages to distinguish between datatypes, you will eventually run into logic problems if you don’t understand their differences. Here are the most common datatypes. Pay attention to the right side of the equations.

Strange things can happen if you don’t pay attention to datatypes, especially when you mix them carelessly. For example, what might happen when you try to perform calculations or comparisons on strings and numbers at the same time? Study the code below and try to imagine what will happen if you run it, then paste it into your sample page and study the results. Are they what you expected?

Notice that some of the combinations make sense and others don’t, all depending on whether we used quotation marks when declaring the variable (i.e. depending on the datatype we used). PHP can be very forgiving … but the fact that it’s forgiving can lead to mistakes. This is one reason why more experienced developers often prefer a stricter language like Python that simply throws errors when you try to do something nonsensical like adding a string to an integer.

More on datatypes in PHP

Working with Dates

In the very first example in this tutorial, we slipped in a sneaker without explanation – a reference to the insanely useful PHP date() function. It’s very common for sites (especially news sites) to render the current date in the masthead or elsewhere. It’s also often necessary to take timestamps stored in a database and render them in various formats — in the dateline of a story, for example.

The date() function gives you great flexibility in how dates should be rendered, letting you work in formats either strict or user-friendly, in normal time or military time, with or without abbreviations. In fact, one of the most visited pages on the php.net site is the date function’s official reference. You’ll see a ton of optional arguments on that page, but don’t worry – you usually only need a few of them. The date() function works like this:

What’s that “l” doing there? Take a look in the function reference and you’ll see that “l” is substituted with “A full textual representation of the day of the week.” So it’s going to display whatever the current day of the week is. You can string the “variables” in the date argument together however you like, with punctuation mixed in as needed. Let’s say you wanted to display:

Monday 8th of August 2005 03:12:46 PM

You’d use the following string of variables in the argument to date():

Look each of these variables up in the function reference to see what role they play.

That’s all well and good for rendering the current date and time, but what if you want to customize the output of a date in the past, such as the dateline for a news article? In that case, simply hand the date() function the date you want handled as a second argument in a valid timestamp format (such as a timestamp emitted from your database), like this:

Conditionals and Operators

A big part of programming is in performing tests. “If the following statement is true, then do something.” “If user is logged in, show the logout link. Otherwise show the login link.” “If the user has checked the I Agree checkbox, then let them download the file. Otherwise prompt them to check the box.” And so on.

A statement that performs a test and does something based on the result is called a “conditional” (because it responds to conditions). The tools a conditional uses to perform tests are called “conditional operators” and are usually of the form “If something is greater than something else” or “If these two strings match” or “If something is true.” So you need to learn conditionals and conditional operators at the same time.

Here’s the general form of a “test” in PHP, using the “if” statement:

Note that you do not use a semicolon after the curly braces – this is a rare exception to the “end every line with a semi-colon in PHP” rule. Often, you’ll want to do one thing if a condition is met, and another thing if it is not:

In fact, you may want to respond to several possible conditions. You can do this with the elseif() statement:

You can have as many elseif() clauses as you like.

Note: As PHP is evaluating the conditions in the block, it will exit the block as soon as the first condition is met. This can mean that tests farther down in the block are never seen by the interpreter if conditions above it are met. In other words, the order of tests in the block can be very important! Think carefully when setting up conditions.

So what goes in those (condition) sections? Usually you’ll be testing to see whether two things are equal, or if one is greater than another. Let’s say you need to determine whether a student has passed a test (assume it takes a score of 70 to pass). Your script might pull test scores out of a database, compare them to a constant (the threshold for passing), and email the student to let them know whether they passed. We’ll re-use the $scores array from earlier.

In this case, we perform a test (line 5) to see whether the array element named ‘Scot’ has a value that is greater than or equal to the currently established threshold for passing the course. Try changing ‘Scot’ to ‘Josh’ to see the script output the opposite result.

Here’s a complete table of the operators you can use. The conditional operators are fairly clear, and you should remember most of them from grade-school math classes. Note that some of the operators are capable of comparing both the value and the datatype of the variable being tested.

Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same
type.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same
type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

Loops

A core feature of any programming language is its ability to iterate, or “loop” through a series of values, performing an operation or testing a condition on each value. There are several ways to loop through values in PHP. A common one is the “foreach” loop, which says “For every value in the following array, do something.” It looks like this:

In practice, you’ll probably want to do something like iterate over the test scores in our $scores array and print out each one. Let’s try that.

In this example, foreach() simply goes through every element in the $scores set and temporarily sets it to $score. It then outputs $score to the screen. Instead of spitting out raw scores, we could easily have put our test from the previous section in between the curly braces, and output something different depending on whether the student passed.

But what about the student names? When looping through an associative array this way, PHP just gives us the values. If you want the student names as well, you’ll have to ask PHP to give you both the “keys” and the values. That’s done like this:

We use the $name => $score (often referred to as $key => $value) syntax to get at both the lookup name and its value.

Another common loop is used to iterate through a certain number of things. For example, a loop that counts to 34 would look like this:

The meat of the action is on line 3, where you’ll find three sections separated by semicolons. The first initializes a counter at 1. The second tests to see whether the value of $counter is less than some number – in this case 34. The third increments the counter up by one (the syntax += 1 means “take the old value of $counter and add one to it.”)

I promised earlier to show you a better way to average any number of numbers without hard-coding the variables or the divisor. Now we have the skills to do that! Let’s return to our indexed array of scores, iterate through it, counting up by one each time through the loop, and doing the final math at the end. Afterwards, I’ll show you an even cooler way to do it, without the looping counter.

Cool, huh? There’s nothing new in this script whatsoever – you’re just putting together things you’ve already learned. PHP, like so many things, follows the 80/20 rule – you’ll use 20% of the features 80% of the time. So how could you write a similar script without a counter? Easy – just count the number of elements in the array instead of incrementing a counter on each pass through the loop:

The built-in count() function does exactly what its name implies – it returns a count of the number of elements in an array.

There’s one more type of loop you’ll see a lot of — the “while” loop. Use this type of loop when you want to keep on doing something until a set is exhausted, or as long as some condition remains true. For example. let’s say your script should pull the most recent four stories out of a database and you want to render each story to the page until you hit story #5, then stop. We’ll use our $scores array here rather than database output, but you get the idea:

When you run the script, notice that it prints only the first four elements of the array, then stops.

The other interesting thing we’re doing here is on line 6. Remember how we access the values of an indexed array with something like $scores[3] to get at the 4th element? But in this script, we’ve written $scores[$counter]. Each time through the loop, $counter is incremented. Since $counter was initialized as zero, the first time through the loop we get the value of $scores[0], the second time through we get $scores[1], and so on.

Working with Forms

The key to almost all interaction between users and servers is through forms, which are used to enter search queries, fill out shopping carts, sign up for newsletters, and so on. We didn’t cover forms in our HTML 101 tutorial because, without server-side processing, there isn’t much you can do with a form. Now that you know some PHP, it’s possible to create interactive forms that do interesting things.

Forms are a fairly complex topic, with many security gotchas to be aware of. This section of the tutorial will acquaint you with form processing, but you should definitely do more reading on forms, security, and PHP before putting forms into production. If your form interacts with a database and you haven’t taken the right precautions, attackers can do very bad things to your site. Better yet, use a well-established framework like Cake or CodeIgniter which takes care of form construction and input sanitization for you. The exercise we’ll do here does not interact with a database and is perfectly safe.

Most forms do one of three things:

  • Perform a search lookup
  • Submit data into a database
  • Generate an email

We need to know how to obtain the value of fields in a form from PHP, so we can do things with them. Let’s take this simple form:

This will give you a simple form into which you can type your name. When you click Submit, notice that the value you typed in your form field now appears in the URL, like this:

http://example.com/tutorial/formtest.php?your_name=Scot

The string appears in the URL because our form used method="get", and that’s what the “get” method does – it appends the form’s field names and values to the URL. Notice also the action="" attribute on the form. You can either leave this blank, or insert a relative or absolute URL. If you insert a URL, the script at that URL will be triggered when the form is submitted. If you insert nothing, the script will submit to itself. That’s what we’re doing here. Notice also that the parameter in the URL has the same name as the your_name input field. If your form has multiple fields, your resulting URL would have multiple parameters.

As we learned at the beginning of this tutorial, we can access parameters from the URL with the $_REQUEST['fieldname'] global variable. So try modifying your script to look like this:

See what we’ve done here? At the top of the document, we jump into PHP mode and do a test (a conditional) to see whether ‘your_name’ is present in the URL parameters. If so, we say hello to that person. Since we don’t have an else{} clause, we do nothing if the parameter is not present.

In many cases, you’ll only want to show the form before the submit button has been clicked. Afterwards, you want to show something else, like a list of search results. We use a similar technique to do that (here’s some pseudo-code for clarity):

It’s almost like we’ve programmed two web pages in one! Here’s actual working code for you to try:

Notice that we do a bit of extra fancy footwork in that example. On line 6, right in the middle of the else{} clause, we exit PHP mode. We’re now back in HTML mode, so we can draw our form on the page. When the form is done, we re-enter PHP mode to close the else{} clause. This is a very common technique.

There’s one big gotcha in the approach we’re using here. What if you were building a login form for a website that requested the user’s username and password? The method="get" technique puts all of the form fields in URL parameters, and you’d end up displaying the user’s password in the URL field, visible to anyone who walked by! Big security no-no.

The solution is to use method="post" instead. POST carries all of the field values in browser memory, but doesn’t alter the URL. But our script depends on the presence of those parameters! Or does it? Try changing “get” to “post” in the script above to see what happens. It still works! That’s because the $_REQUEST global variable contains everything in the browser request in memory. In fact, we never did say “Obtain the value from the URL” – we said “Obtain the value from the $_REQUEST global variable,” so we’re all set.

In general, use the GET method for forms when you want the URL to carry the parameters, as in search requests. Use POST at all other times.

Again, please read up on forms and security before deploying them, especially if your script is talking to a database. Or better yet, use a web framework such as Cake or CodeIgniter to do the heavy lifting for you.

Working with Databases

Throughout this tutorial, we’ve been talking about how your data sets often come from a database, and about how PHP has lots of tools built in for getting data out of (or putting data into) a database. But how exactly does that work?

Before you can continue, you’ll need a database to work with. Your web hosting control panel should provide some kind of interface for creating new databases, and for giving them usernames and passwords (all database connections need to be authenticated with custom credentials, not with your username and password at the web host.) Find that control panel and create a new, blank database. Save the database name, username, and password in a file – you’ll need them in a minute.

On many hosts, you’ll need to create the database, create a db user and password, and then give that new user permission to access the database. Give the new username all necessary permissions to use the new database. Return here when your database has been set up and you’ve successfully given a db user permission to use it.

Giving a database user permission to use a particular database. You must do this before PHP can be configured to speak to the database.

Your control panel should also provide some kind of management interface onto the databases you control. On most hosts, it’s called phpMyAdmin. Look for phpMyAdmin or other database management tool at your web host. Open it up and select your blank database. Within that interface, you’ll see a button or panel labeled SQL. Click that. You should be looking at something similar to this:

Find the SQL field in your database management tool. Here’s the one provided by phpMyAdmin.

Rather than have you create database fields from scratch, I’ve created a small sample table you can load into your database quickly. Copy the following SQL code to your clipboard, paste it in the empty SQL field, and click Go (we’re not going to get into explaining SQL in this tutorial – suffice to say that SQL stands for Structured Query Language, and is used for interacting with databases independently of particular programming languages).

A new table should be created in your database. Select it, then click the Browse button in your database management tool. You should see something like this:

At this point, we’ll assume you’ve verified that the table exists and that your sample data has been loaded. Now, back to PHP. Let’s start by writing a script that will pull all records from the database and display them in a table. Notice that we’ll put the table header in HTML mode, then generate the tables rows and cells from within PHP mode, and finally switch back to HTML mode for the table footer.

On lines 8,9, and 10, replace the placeholder values with the database name, db username, and db password you established earlier. Line 11 will probably work as-is, unless your web host has provided an alternate “host” or “database server” that you should be using. If the credentials aren’t correct, you’ll see some messy error output when you try to pull up the script. If so, go back to your host’s database management interface and confirm the db name, username, password, and host/server.

If all went well, you’ll see the data in your database in a neat little table. Let’s step through the code. Lines 12 and 13 set up a connection to the database server and select the database we want it to use. Line 15 gives us some basic error checking in an if/else statement, so we can report back to the user if the database connection could not be made.

Line 17 creates a variable containing a bit of SQL code to make a query against the database (it says simply, “give me all fields of all records” – in practice you’d want SQL here to limit the number of records and fields by some criteria, such as “Give me the headlines and blurbs of all articles published in the past week,” but advanced SQL is another tutorial.) Line 18 actually executes the query you just set up.

Line 20 looks a bit familiar – remember when we learned about while() loops earlier? Here we’re saying “Loop through rows in the query results until they’re exhausted, and save each row temporarily in an array of fields, called $db_row.”

On the following lines, we emit HTML table code, where the contents of each cell is an element from the current array $db_row — just like we did when iterating over arrays earlier in the tutorial.

On line 31, we close the “handle” on the database so it doesn’t take up memory in PHP. This line just says “I’m finished for now.”

Pretty cool, huh? Now, what if we want to insert a new row into our database? Try this code:

The code here is pretty similar to the previous script, except that it runs a SQL “insert” query instead of a “select” query. Run the script, then pull up the script from the previous example to confirm that new data is now in your database.

We set variables for the values to insert into the database on lines 12-13. Then on lines 18-27, we convert those variables into an actual SQL query. Since we’re inserting rather than selecting data, we’ve removed the HTML table generating code. In actual practice, the data would probably be obtained from form input, but we’ve hard-coded it here for illustration purposes.

You can write similar scripts to update or delete existing records – learn the SQL statements for those actions and see if you can modify these scripts to perform them!

Conclusion

This has been a very cursory introduction to PHP – just enough to get your feet wet and be off to the races. Believe it or not, you now know enough to look at the code for most content management systems and basically understand what they’re doing – maybe even to modify them! If you’re feeling ambitious, try building your own PHP scripts from scratch. Remember, it’s practically a right of passage to write your own blogging engine or content management system (though I wouldn’t recommend putting one into production – that wheel has been invented many times over).

PHP is truly a “Swiss Army Knife” for web developers, and can be used for solving problems large and small in thousands of web publishing environments. Remember – just reading about programming isn’t going to get you off the ground. The more time you spend writing actual, working code, the more capable you’ll become. Enjoy the process!

About this Tutorial

This tutorial was written to accompany Scot Hacker’s Web Development Basics course at the UC Berkeley Graduate School of Journalism, but should be useful to anyone looking for a solid introduction to the language.

Republishing Policy

This content may not be republished in print or digital form without express written permission from KDMC. Please see our Content Redistribution Policy at kdmc.berkeley.edu/license.