The Web, Untangled

◀ MySQL Table of contents AJAX ▶


1.1 PHP file structure

PHP files look a lot like HTML files. The difference is that they have some extra code embedded inside - this code runs on the server and can be used to query your database and generate some extra HTML to display.

PHP files always end in .php, but they can also contain HTML code You just need to start with this tag:


…and finish with this tag:


The following code shows where you would typically put the <?php and ?> tags: inside the <body> tag of the html file:

    The Skeleton of a PHP Application



    // Your PHP code will go here



PHP tags can be put anywhere inside the file, however - functions are sometimes put inside the <head> tags and used from extra PHP code inside the <body> tags.

1.2 Printing

PHP is useful because it can generate extra HTML code for you. It does this by "printing" strings to your HTML page. These strings can even be HTML tags!

To print something in PHP, use the "echo" function:

echo "Hello, PHP!";

To print a newline character, insert an HTML <br>:

echo "Hi,<br>How is it going?";

Try typing this code into a file called index.php in a new folder called phptest in your server's htdocs folder:

    The Skeleton of a PHP Application



    echo "<h1>Hello, PHP!</h1>";
    echo "<p>This is a test - does the HTML get printed?</p>";



Now open up your web browser and go to http://localhost/phptest. You should see the friendly test that you just typed, rendered in glorious HTML.

WARNING: do not click on the .php file to open it in your browser. If you do this, the php code does not get executed. The best way to check is to look at the address bar: does the URL begin with "localhost"? If so, that's great. If it starts with "file:///", then the code is not being run by the server (it will probably just print your PHP code out instead).

1.3 Variables

PHP is a "dynamically typed" language. That means that you don't have to tell it whether a variable is an integer (number), string (piece of text) or any other type ahead of time. It tries to work it out for itself based on what you give it.

To declare a variable, its name must start with a dollar sign ($)

$age = 32;
$myName = "Matt";

In the above code, the $age variable ends up as an integer, and $my_name ends up as a string type. You don't have to worry about that too much at the moment, but bear in mind that this can be an unexpected source of errors when you try to treat a string is an integer and vice versa!

1.4 String Concatenation

To print strings and variables, put a dot (.) between them:

echo "My name is " . $myName . " and my age is " . $age . "<br>";

A quick way to insert variables inside your strings is to put them inside double quotes ("). This doesn't work with single quotes, though:

echo "My name is $myName and my age is $age<br>";

Be careful though - this only works for simple variable names, and may not work if you are doing anything a bit more complicated (like getting items from an array). If in doubt, always go back to using the dot (.) to concatenate the strings with the variables.

1.5 Arithmetic

PHP has all the usual arithmetic operators:

2 + 3;
3 - 4;
3 * 3;
44 / 3;
23 % 4;

But it also arithmetic assignment operators. These change the value of a variable in place:

$x = 1;

$x++; // now x is 2
$x += 1; // now x = 3
$x -= 4; // now x = -1
$x *= -4; // now x = 4
$x /= 4; // now x = 1

1.6 Data Types

As mentioned before, PHP is a dynamically typed language where you don't need to specify the types of variables. They do get assigned types behind the scenes though, so it's good to know what they are:

$myName = "Matt"; // string
$myAge = 32; // integer
$myHeight = 186.4; // double
$isTeacher = true; // bool
$nullVal = NULL; // NULL

1.7 Conditional Statements

PHP has if, elseif and else statements, they work the same way as almost every other language:

$food = "curry";

// if statement:
if ($food == "pasta") {
    echo "I like pasta"; // this code is executed if $food is "pasta"

// if and else statements:
if ($food == "pasta") {
    echo "I like pasta"; // this code is executed if $food is "pasta"
} else {
    echo "I don't like pasta"; // this code is executed if $food is NOT "pasta"

// if, elseif and else statements:
if ($food == "pasta") {
    echo "I like pasta"; // this code is executed if $food is "pasta"
} elseif ($food == "curry") {
    echo "I like curry"; // this code is executed if $food is "curry"
} else {
    echo "I don't like pasta"; // this code is executed if $food is NEITHER "pasta" or "curry"

1.8 While Loops

A while loop will keep repeating while the condition is true:

$cond = true;

while ($cond == true) {
    echo "This code will print over and over.<br>";

1.9 For Loops

A for loop has three parameters: some initial statement, a conditional statement which stops the loop if false, and a statement which run after every loop:

for ($i = 0; $i < 10; $i++) {
    echo "i is " . $i; // this will print numbers from 0 to 9

This works the same as in other languages. Don't forget to put the dollar sign ($) in front of whatever index you use (in this case, $i).

1.10 Arrays

To create an array variable in PHP, put the elements inside square brackets and separate them with commas:

$weekDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

The old-school way to do this (compatible with PHP versions before 5.4) is with the array() function:

$weekDays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");

Either way is fine, but using square brackets is a convention for most languages, so is easier to remember.

As PHP is a dynamic language, you can mix different types in the same array:

$mixedTypes = ["hello", 12, [132, "yes"], 28.22, "bye", true];

Use the arraypush() function to add elements to an array. This changes the value of the array in-place (rather than returning the changed array):

echo $weekDays; // ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

array_push($weekDays, "Saturday", "Sunday"); // Note that this takes each new element as an extra argument

echo $weekDays; // ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

1.11 Foreach loops

Foreach loops are a very convenient way to go through each element of an array:

// this prints each element of the $weekDays array
foreach ($weekDays as $w) {
  echo $w . "<br>";

Each time it goes through the loop, $w is given the value of an element from the array. So in this case, the first time round $w = "Monday", then $w = "Tuesday", then $w = "Wednesday", etc.

1.12 Associative Arrays

Associative arrays (also called "Hash maps" or "Dictionaries" in other languages) hold pairs of keys and values. A key is used to look up a value that is associated with it. For example:

$person = ["name" => "Matt", "age" => 32, "height" => "186cm", "favourite_food" => "curry"];

The "fat arrow" (=>) goes between each key - value pair, so the template is:

key => value

You can then use a key to look up its corresponding value:

echo $person["name"] . " is awesome<br>";
echo "His favourite food is " . $person["favourite_food"] . ".<br>";

// With the above example, this prints:
// Matt is awesome
// His favourite food is curry.

Foreach loops can also be used to go through the items in an associative array:

foreach ($person as $key => $value) {
  echo $key . " is " . $value . "<br>";

// With the same example, this prints:
// name is Matt
// age is 32
// height is 186cm
// favourite_food is curry

The above goes through each item of the associative array and assigns its key to $key and the corresponding value to $value.

2 Using Web Forms with PHP

2.0.1 GET vs POST requests

When you make an HTML form, you can specify the type of request that is sent:

<form action="script.php" method="post">

The two types of requests that you need to know about are GET and POST requests. The default (in case you don't specify the method) is to use a GET request. GET requests are sent by adding information on to the end of a URL. For example, if you type "Matt" into a text box called "name" and "32" into another text box called "age", this will appear at the end of the URL:


When this is sent to your index.php file, the full URL in the bar appears as:


But what if you have some valuable information that you don't want to be exposed in the URL of a page? You can imagine how this could be a security risk - you don't want to see a password you've entered into a web form to appear in the URL, for example. To solve this problem, you can use the POST request, which sends the information invisibly.

So why use GET requests at all? Well, they can be useful in case you want to send or link to a URL with the certain parameters included. For example, if you have a web shop with a "products" page, and the product shown is dependent on parameters sent via GET, you could link to that product like this:

2.0.2 PHP $_GET and $_POST superglobals

Once you've sent the data to a PHP page using your web form, you need to access it using a superglobal variable. This changes according to the method you've used to send the data. If you used a GET request, you'd bind the form data to variables using $_GET['']. Take this HTML form, for example:

<form action="script.php">
  <input type="text" name="username">
  <input type="number" name="height">
  <input type="date" name="birthday">
  <input type="submit" name="Submit">

Note the names for each text box: "username", "height", and "birthday". These are the keys that we use for the $_GET superglobal:

$username = $_GET['username'];
$height = $_GET['height'];
$birthday = $_GET['birthday'];

If you've used a POST request instead, you can access the data with $_POST['']:

$username = $_GET['username'];
$height = $_GET['height'];
$birthday = $_GET['birthday'];

You can then use the form information using the variables you've declared.

3 Accessing MySQL Databases with PHP

We will now use the mysqli interface to connect to MySQL database from PHP code. The mysqli interface has two different ways of using it: the object-oriented way and the procedural way. We will be using the procedural API throughout this book.

3.1 Connecting to a MySQL database with PHP

First, you need to create a file called index.php somewhere on your web server. For example, if you put it in a folder called "mysql" inside XAMPP's htdocs folder, it will be accessible at this address: http://localhost/mysql. Put the usual skeleton of an HTML file inside:

<head><title>PHP and MySQL</title></head>


        // Your PHP code goes here



The next step is to create some variables to hold the login details for the MySQL database:

$host = "localhost";
$username = "matty";
$password = "password";
$db = "mydatabase";

We will refer to these variables when we create the database connection. This is done by using the mysqli_connect() function:

$connection = mysqli_connect($host, $username, $password, $db);

When we call the mysqli_connect function, the result is stored in the $connection variable. This is used to store the state of the connection to the database, so that we can use it to query, make changes and close the connection when we are done.

To check that the connection succeeded, use an if-statement:

if($connection === false) {
    die("ERROR: Could not connect." . mysqli_connect_error());

echo "Connection successful";

This checks to see if the connection was successful, then terminates the PHP script with an error message if not. If it did succeed, it prints "Connection successful".

The full, complete code for connecting to the database is listed in this file.

3.2 Querying the database with PHP

Now that we have connected to our database using PHP, we can send some SQL queries to it. In this example, we're going to get all of the entries from a table called "users", then go through the results row by row, printing only the values in the "name" column.

First, we'll create a string for our SQL query and assign it to a variable called $sql:

$sql = "SELECT * FROM suspect;";

Then we can send it to our database for execution:

$results = mysqli_query($connection, $sql);

The results (every row in the suspect table) will then get bound to the $result variable.

Now, you would expect $results to be an array that contains all of the rows that the SQL query returns. But no, that would be too simple! It instead returns a mysqli_result object. To get the rows back out of this object, you can't treat it like a standard array - you have to call the mysqli_fetch_array() function on it. This is best done inside a while loop.

while($row = mysqli_fetch_array($results)) {
    echo $row['name'] . "<br>";

You should wrap this in an if statement that checks to see that some results have been returned - if they're not, then $result will be false, and your code will break (because mysqli_fetch_array() expects an object, not false):

if(mysqli_num_rows($results) > 0) {
    while($row = mysqli_fetch_array($results)) {
        echo $row['name'] . "<br>";

It's kind of like we're saying: "while there's a result left to fetch, fetch it and assign it to $row. Then print it."

What if there's something wrong with the SQL command? You probably want to print an error message so that you can debug it. You can do this by adding die(mysqli_error($connection)) to an else statement at the end:

// This code connects to the database and sends the sql query to it,
// then it prints all of the results
if($results = mysqli_query($connection, $sql)) {
    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_array($results)) {
            echo $row['name'] . "<br>";
} else {

While this may appear to be a reasonably daunting piece of code, don't worry too much about it - you can get away with copying and pasting it a lot of the time. The part that you will have to change is the $echo $row['name'] . "<br>"; line in the middle. For example: instead of printing the results, you could add them to an array to use later.

The full code for querying the database is in this file.

3.3 Creating a new database

The full code for creating a new database is in this file.

3.4 Creating a new table

The full code for creating a table inside a database is here.

3.5 Using a HTML form to add rows to a database

The code for the HTML form page is here. The PHP code for handling the GET request is here.