Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

MANG6531  Computer Lab Session 2: Server-Side Scripting using PHP

Whereas last week's session focused on client-side technologies, the main aim of this week's session is to let you experiment with PHP server-side scripting so as to:

•    Gain a basic understanding of PHP and how it can be used to implement server-side functionality such as the processing of forms and database access;

•    Become familiar with the PHP and MySQL configuration you will be using for your individual assignment.

To create the suggested PHP scripts, we suggest you again use Sublime Text.

These activities assume you have gained a basic knowledge of HTML from last week's lab session.  Although we won't be doing anything too complicated at the database level, you will also be introduced to the use of SQL to query a relational database.  Similarly, to the previous session on JavaScript, this session is again meant to help you get started.   To continue learning more about the PHP language, links will be provided at the end.

Activity 4: hello world PHP script

Our first activity will be to write, upload and test a PHP script that produces a page displaying a simple hello world” message.

All the PHP scripts you will produce in this session have to be uploaded to your personal webspace  a resource provided by the University.  Last week, that wasn't yet necessary, as client-side technologies run perfectly fine on your local computer.  In contrast, a PHP script can only be run by a web server.  Hence, we will have to put it on a University web server that was set up for this purpose, and then access the corresponding URL from a browser, just as any other visitor would do.

Note that, if you would be doing these activities from home, or on your own computer, you may also need to set up a VPN first.1

To test whether you can  upload files to your  personal webfolder, select Run” from the Windows start menu and then enter the following network path:

\\filestore.soton.ac.uk\personalwebfiles

 

On a Mac, Open Finder, click “Go” on the menu bar at the top and choose “Connect to Server” and  enter  the  following  path:  smb://<your  username>@filestore.soton.ac.uk/users/<your username>

•   Replacing <your username> with your actual username

•   You will be prompted for your username and password

•   If your username and password combination doesn't work, try entering your username as SOTON\<your username>”

This should open a new window showing you the contents of your personal web file store (which is still empty for now).  This is where we will copy and paste our PHP scripts into.

Let's now create our first hello world” PHP script.  Start Sublime Text, Type in the following PHP code:

<?php

echo "Hello world!";

?>

Note that PHP's echo statement, when seen by the web server, will result in text being written (or “echoed”) to a dynamically produced HTML document in this case, the intended Hello world!” message.  Each PHP script must start and end with <?php and ?>, respectively.

Name this new file “helloworld.php” and save it to your desktop.  Make sure the file name ends with the extension “ .php” .  That way, our web server will know it needs to interpret any PHP script(s) embedded in the file.  Next, you will have to upload this file onto your personal web space.  You do that by copying and pasting your PHP file into the network folder window you opened earlier (if you lost that window, select Run” again and retype the network path; see previous page).

Now that the file is there, you can access it using your preferred browser (e.g. Chrome, IE or Firefox), at the following web address: https://www.southampton.ac.uk/~<username> (type in the URL in the address bar but substitute <username> with your own user ID, don’t forget the tilde symbol (~) and make sure you use the exact same capitalisation as in your file name!).  If all goes well, the server will successfully run your script and send the result back to your browser, which should now display a single-line document that simply says, “Hello world!” .

As we learned in the lectures, PHP is a server-side scripting language.  This means the PHP script that you wrote is processed by one of our University's web servers which have been set up to interpret PHP scripts accordingly – not by your own computer (you can't just double-click the PHP file on your own machine).  The result of this processing is an HTML document that is then sent to your browser.  The user at the client-side (that's just you for now) can only see that HTML document, not the original script that produced it. Check what HTML code was produced and sent from the server side by right-clicking on the web page and selecting “View Source” (Internet Explorer) or View Page Source” (Firefox). You'll see the HTML only consists of a single line “Hello world!” and does not yet have a proper header and body section, like we learned last week. Your browser is smart enough though to assume the Hello world!” is meant to be some text in the document body.

One of the features of PHP is that you can mix “static” HTML markup (i.e., for the parts of your HTML page that are always the same) and one or more PHP scripts (to create dynamic HTML content).  The dynamic content is inserted, line by line, into the resulting HTML document, using PHP's echo statement.  The content to be inserted is again specified between double quotes and the location where the echo statement appears in your file determines where that content is inserted.  Let's modify our script as follows to illustrate this:

 

<html>

<head>

<title> Activ. 4: Hello world PHP script </title>

</head>

<body>

<h1>This is a message from your Web server:</h1>

<p>

<?php

echo "Hello world!";

?></p>

</body>

</html>

Make sure you save this modified version and copy it again onto your personal web store. Try reopening the script in your web browser (type in the same URL you used earlier or refresh the page) and check whether it displays correctly the page should now have two lines a

header and a paragraph:

Where static        HTML appears in the original file, it is just reproduced line by line

Check again what HTML code was produced and sent from the server side by right-clicking on the web page and selecting View Source” (IE) or View Page Source” (Firefox).  See how the output of the PHP script (not the actual script itself!), i.e. the Hello world!” text inside the paragraph, was inserted into the rest of the markup.  Alternatively, you could have produced the entire page dynamically using only PHP statements, but mixing both is usually more convenient: The  more standard  HTML  is  included  in the  pages, the easier they are for designers or front-end developers to amend without asking the back-end developer for help.

Obviously, if a PHP script would always be echoing the same content, this would not be particularly helpful.  Let's learn next how that content may depend on the data stored in some database whose contents may change over time.

Activity 5: Retrieving Data from a MySQL Database

In our previous lab session on HTML and JavaScript, we created a HTML form in Activity 1. Look up the solution file Activity1.html” and inspect it again.  Inside this file, a HTML table was defined containing a small product catalogue consisting of three items and their prices.  Next, instead of hardcoding this  product catalogue  into  HTML, we will write a  PHP script that retrieves these products at run-time from the contents of a database table.  For the purpose of this exercise, a MySQL2  database, named “mgmt_webapp_msc” , was created and stored on a small University server (srv02958.soton.ac.uk– no need to access this from your browser!). This database contains a table “products_class” defined as follows:

i(-)e(-)l(-)d(-)y(-)p(-)e(-)u(-)l(-)l(-)e(-)y(-)e(-)f(-)a(-)u(-)l(-)t(-)x(-)t(-)r(-)a(-)----------

+-----------+-------------+------+-----+---------+----------------+

| prod_id   | int(11)      | NO   | PRI | NULL    | auto_increment |

e(_)

+-----------+-------------+------+-----+---------+----------------+

Note how the three product attributes stored in the table are: an integer-valued product ID; the product name (a text field with a maximum of 50 characters); and a unit price.

This table currently holds three records, as shown below:

 

+---------+-----------------------+-------+

|       1 | Record Cleaning Brush | 12.20 |

 

+---------+-----------------------+-------+

You  are  given  access  to  execute  SELECT  queries  on  this  table  under  the  user  name: MANG6180_student, password: tintin1830.

Use Sublime Text to create the following PHP script and name it Activity5a.php” (make sure you use the .php extension; to save time typing, you could skip the lines starting with // as they are only comments meant to explain what the next line is about):

<?php

//connect to DB host, or show error message and end script if unsuccessful

$mysql = mysql_connect("srv02958.soton.ac.uk", " MANG6531_student",

"tintin6531") or die("Connect failed!");

//select the database

mysql_select_db("mgmt_webapp_msc") or die(mysql_error());

//formulate SQL query to obtain product information

$get_products_sql = "SELECT prod_name, price FROM products_class";

//send query and store result set in $result

$result = mysql_query($get_products_sql) or die(mysql_error());

//go through the result set, putting each row into an array $result_row

while ($result_row = mysql_fetch_array($result)) {

//put the row details into two variables $prod_name and $price

$prod_name = $result_row['prod_name'];

$price = $result_row['price'];

//output both

echo "<p>$prod_name: $price</p>";

}

?>

Upload the script to your personal webspace, and try opening it in your web browser first.  If everything is working correctly, you should see the following output:

Record Cleaning Brush: 12.20

Record Cleaning Cloth: 2.40

Anti-Static Gun: 72.00

Also, have another look at the HTML code of the generated page by right-clicking on the web page and selecting View Source” (Internet Explorer) or View Page Source” (Firefox).  Note again how the PHP script is no longer visible; we only see the HTML produced by the echo statements in the script:

<p>Record Cleaning Brush: 12.20</p><p>Record Cleaning Cloth: 2.40</p>

<p>Anti-Static Gun: 72.00</p>

So far so good.  Let's now examine the PHP script that we just wrote in some more detail.

First of all,  note how comments were  included to explain the code.   In  PHP, single-line comments are preceded by //, or multi-line comments can be enclosed between /* and */, similarly to many other programming languages.  This tells the PHP interpreter that these bits are not actual program code but some documentation about what the script does.

PHP, depending on the version, has two different interfaces for communicating with MySQL databases: the mysql_* family of functions and the more recent mysqli_* family of functions.

Bear in mind that our web server is still configured to work with the first function set, not  the  second!    The  script  uses  several  such functions  using which  you  can  already implement the most common database tasks:

•    mysql_connect(hostname, username, password):  sets  up  a  connection with the MySQL host using the specified parameters;

•     mysql_select_db(database): selects the database to work with;

•    mysql_query(): used to issue SQL queries; in this example, we only needed a simple SELECT  query,  but  you  could  e.g.  also  execute  INSERT,  DELETE,  CREATE  TABLE statements, etc.

•    mysql_fetch_array(): used to navigate through the SQL result set; returns an array that corresponds to the fetched row and moves the internal data pointer further ahead (i.e. to the next row) each time you call it; returns false if there are no more rows.

•    mysql_error():  returns  the  text  of the  error  message  from  the  previous  MySQL operation.

There are several similarities in syntax and semantics between PHP and JavaScript.   For example, variables (in our script: $prod_name, $price, etc.) are not type declared (but unlike with JavaScript, PHP variables must be preceded by a dollar sign), the available control statements (see e.g. the while statement used in the script) are quite similar, etc.  However, PHP arrays (used to store lists of items) are more flexible than in many other programming languages.   For example,  in the script above, mysql_fetch_array() returns a so-called associative  array  whose  elements  can  be  addressed  using  actual  named  keys  (as  in $result_row['prod_name'], $result_row['price'], etc.) rather than with numeric indices ($result_row[0], $result_row[1], etc.).  Next refer to w3schools.com to find further details on the following language constructs used in your script:

•     http://www.w3schools.com/php/php_variables.asp: declaring PHP variables;

•     http://www.w3schools.com/php/php_arrays.asp: more explanation on PHP arrays;

•     http://www.w3schools.com/php/php_looping.asp: the while loop, which we are using to go through the contents of the products database table, row by row.

So far, we have seen how to write a simple server-side script that retrieves data from a database table.  Of course, we didn't exactly end up with the most intuitive of interfaces yet, so let's complete this activity by putting some more markup into what we have so far, and write the output of the script to a HTML table instead of formatting it as plain text paragraphs. The aim is to end up again with something looking as follows:

 

Start a new script, copy and paste whatever you can use from previous or current activities, and try completing the script.  Essentially, what the script does or should do is this: rather than echo a HTML paragraph for each respective product, instead echo a HTML table row.  Recall from last week that a table row starts with <tr> and ends with </tr>, and inside of it, you should specify a table data cell (starting with <td> and ending with </td>) for each column (if needed, go back to last week's exercise to refamiliarise yourself with the HTML table syntax). Try to have a go at this yourself hint: start by changing the echo string from the previous exercise so that it now includes the HTML markup for a table row, with the correct variable names ($prod_name, $price, etc.).

Once you are done, or if your attempts are unsuccessful, please look up the solution on Blackboard (Activity5b.php) and try to analyse it in detail.   Have a closer look at what the following statement in the solution script is doing:

echo "

<tr>

<td>$prod_name</td>

<td>£$price</td>

</tr>";

This statement is executed three times (for each product fetched from the database) and it writes the three HTML table data rows based on the contents in that database.   If those contents change because we update our product catalogue, the next time the page gets loaded, its HTML contents will be instantly updated.   In other words, unlike in last week's exercise, we no longer have hard-coded our product catalogue into static HTML; instead, we have a much more maintainable solution that uses server-side scripting to present an up-to- date product catalogue whenever the page gets accessed.

To better understand how the script works, try making some changes and see how that affects the HTML source code that is produced.

Activity 6: Processing HTML forms using a PHP script

In Activity 1 of our first computer lab session, we have already learned how to design a HTML form to receive user input.  So far though, we did not yet specify any action”, i.e. code to execute when the user clicks the submit button (see the HTML snippet from Activity1.html below: no value is specified for the action attribute).

<form action = "" method = "post">

(…)

</form>

In this activity, we will see how to actually process the information supplied by the user.

Download a copy of Activity1.html from Blackboard and rename it Activity6.html.  Edit the file by going to the start of the form section; replace action = "" by action = "Activity6.php", i.e. the name of a new PHP file that will be used to process the form.  Create a new script with that same name (Activity6.php).  Include the following code in that new script:

<?php

echo "<p>Thank you <b>".$_POST["name"]."</b>!</p>";

echo "<p>You have chosen to pay using <b>".$_POST["payment"]."</b></p>";

?>

Upload both files (Activity6.html and Activity6.php) to your personal web store and open the HTML page in a web browser (https://www.southampton.ac.uk/~<username>/Activity6.html). Fill in a name in the form, and then click on the submit button.  If all goes well, your browser should execute the accompanying script (Activity6.php) and display something as follows:

Thank you, Joe! 

You have chosen to pay using visa

As you can see, the form data entered by the user can be accessed using an array variable named $_POST[].  The elements in this array are simply indexed using the name given to the corresponding HTML form element. Check that “name” and “payment” were indeed the names we specified for both form elements (look up the name attribute in both form elements).  This explains why we were naming each input element last week to later on access the contents in a server-side script.

Note: This example script so far only produces a customised confirmation message, but it does not actually store the customer's order in a database yet.  If the database were set up to have another table to receive and store customer orders, adding a few extra lines of code that issue an INSERT SQL statement would do the trick. This is not something you will need for this year's assignment though.

Activity 7 (optional): Using query strings; mixing PHP and JavaScript

While browsing the Web, you will have undoubtedly seen URLs that looked somewhat like “www.somesite.com/somepage.php?id=123&lang=en”?     Such  a  page  is  being  passed variables through a query string (the part of the URL after the “?”).   In this example, the variables “id” and lang” are being passed, with values “123” and en”, respectively.  These values can then be used in the script (e.g. to look up id=123 in a database table, and present the resulting page in the right language).3

I have included two more files on Blackboard, “Activity7a.php” and Activity7b.php”, which show you how to do this in PHP.  Download both from Blackboard and upload them to your personal web store.   Try out the first file by typing the correct URL in your web browser's address bar.  It again builds a HTML table based on the products in our database table, but now each product is represented by a HTML link.  Open the script in Sublime Text and have a closer look at the URL associated with the link: It refers to the second script, Activity7b.php, adding a query string in which the ID of the selected product is passed on. Try clicking on one of these links in the browser and you should arrive on a second page in which you can specify the quantity you wish to order and calculate the resulting price.

If you have a look inside this second script, you will see that it uses the id parameter passed in the query string (accessible through the $_GET[] variable, similarly to how we used $_POST[] in the previous activities) to construct a database query.  That database query fetches the corresponding product details.  Elsewhere the file contains some JavaScript to calculate the price total based on the unit price.  Note how a small PHP script is used there to substitute the correct unit price retrieved from the database.  Prior to all of this, in the beginning of the script, some elementary checks are done.  These are needed if e.g. the user would type in the URL directly, without a valid query string.

Examine the program code and see whether you can piece together what happens at each step based on what we have learned up till now.  Bear in mind this is getting quite a bit more complicated than the examples we have seen so far, so if you get lost, don't hesitate to ask!

Conclusion

This is where our first encounter with PHP ends.  At this point, we have seen how to write some basic PHP scripts allowing us to interface with MySQL tables and process form input, and we have dissected a more complicated example showing how one can mix PHP and JavaScript.  Starting from the concepts we have encountered so far, you should already have a fair idea of how some common server-side functionality can be implemented.

What do you need for your individual assignment?

For your individual assignment, there will be some PHP coding required, not unlike that of Activity 5, as you will be asked to display a list of photographers stored in a database table. You may decide to present this in the form of an HTML table, as in today's activity, or in another format that you feel is more suitable for the design you have chosen.  You will not have to process any form input though, nor update the database.

Where to find more

Once you have finished these activities, I suggest you learn more about PHP by consulting an online tutorial or using one of the many textbooks available.  As it is likely that you will only need a limited amount of PHP code for the individual programming assignment, you can also choose to learn more on the fly”, as you work your way through your assignment.  Below are some suggestions of useful websites.

First of all, the official PHP website, www.php.net, has a large archive of PHP-related material. See http://www.php.net/manual/en/tutorial.php for a first short introduction.

A  detailed  reference  manual  can  be  found  at:  http://www.php.net/manual/en/index.php. Here you can e.g. look up the documentation for specific PHP functions when it turns out you need them for your assignment.   A good step-by-step  PHP tutorial can be found on W3 Schools: http://www.w3schools.com/php/default.asp.

If you need any help with your SQL query, an explanation of the syntax along with examples can be found at https://www.w3schools.com/sql/default.asp but you will not need anything beyond a simple SELECT query to complete the assignment task (no where’ clause, no aggregation, no joins, etc.).  So going through the first few pages of the tutorial will suffice.

Note that we recommend you do your programming assignment using just the web server and database server we have set up for you.  However, if any of you would like to experiment a bit more and set up a full development environment from scratch on your own machine, you might want to have a look at one of the several online tutorials explaining how to set up and configure Apache, PHP, and MySQL, on a Windows PC. Alternatively, a package such as WAMPserver (available     from:      http://www.wampserver.com/en/)     or     XAMPP     (available     from: https://www.apachefriends.org/index.html) should set up Apache, PHP and MySQL in one go. Careful though: these packages are likely to install a more recent version of PHP than the one we are using; hence, your solution might work on your local installation but still needs to  be changed to  run  in our  network environment!   For that  reason,  I would recommend NOT using these for the purpose of the assignment.   Please check with your module lecturer if you would get confused about any of this, and do not leave testing to the last minute.