6 April 2012

CMT3313 - Week 7 Post - PHP Technology

Last week's post consisted of server-side technologies and today I am going to write about, what is probably the most widespread server-side technology out there and this is knows as PHP.


I will be dividing this post into 3 part like so:

  • What is PHP?
  • What is XAMPP?
  • Creating a simple PHP project using Netbeans 7.1 IDE
PHP Logo
What is PHP?
PHP stands for PHP:Hypertext Preprocessor  and it's an open source, server-side scripting language, similar to JSP and Microsoft's ASP.
Basically a PHP file is made out of normal HTML code, but with embedded PHP scripts via the opening <?php and closing ?> tags. PHP scripts are used for various reasons, such as arithmetic calculations, database querying and probably the mostly used, dynamic generation of HTML.

How does it work?

PHP is executed on the hosting server, generates the HTML and sends it to the client as a normal HTML page. This method has an advantage over JavaScript as the client is not able to view your PHP source code as he/she is only receiving the generated HTML, whereas in JavaScript, being a client-side scripting language, has no other option other than sending the source code to the client machine.


XAMPP
What is XAMPP?
XAMPP is an Apache distribution which provides an easy way to install and monitor Apache web server, MySql database, PHP and various other applications typically used on a web hosting server.

Visit http://www.apachefriends.org/en/xampp.html to download a distribution and install it. I have installed mine ages ago, so I will not be using this post as an installation guide. But don't be afraid to do this as it's very simple to install and if any problems arise, there are tons of guides out there to help you out.

Creating a simple PHP project using Netbeans 7.1 IDE
N.B. - To carry out this example your selves, make sure you have already installed XAMPP on your machine.

PHP is known for being easy to use for beginners, so lets test it out a bit shall we.
Mind you this is my first time using PHP, so I'm going to keep it simple and create an HTML page which displays records from a table I have in MySQL.

Step 1
Open Netbeans and click on the New Project button at the top right.


Step 2
Choose PHP from the categories section, select PHP application from the projects section and click on the Next button.



Step 3
Netbeans will automatically scan your machine for the XAMPP document folder and set this as the source location. Give a name to the project and click on the Next button.



Step 4
This step is used for setting the run configuration, make sure the 'run as:' value is Local web site as for this example we will be using the Localhost, which refers to the hosting server on your machine. This could also be referred to as IP address 127.0.0.1



Step 5
This step is used to select a PHP framework but I decided not to select any and clicked on the Finish button.

Congratulations! You have now created your own PHP project...but it really doesn't do anything yet. 
So lets continue by creating a simple HTML table which displays the data retrieved from some SQL query. I decided that I want to display the data I have in my sales_order table located in MySQL.

As I've said before, when tackling something new, the best thing to do is divide it into multiple sub-tasks. I divided mine like so:

  1. HTML table
  2. HTML table headers
  3. Connect to MySQL via PHP
  4. Execute an SQL query via PHP
  5. Generate HTML table rows via PHP

Now I am assuming that if you are reading this post, you must have some knowledge of HTML already, therefore you must already know how to create an HTML table with headers, so I will not be going into much detail about that and jump straight to the PHP bits.

        <h3 align="center">Sales Order</h3>
        <table border="1" style="width: 100%" align="center">
            <thead style="background-color: #000033; color: #FFFFFF" >
                <tr>
                    <th>order_number</th>
                    <th>customer_number</th>
                    <th>product_code</th>
                    <th>order_date</th>
                    <th>entry_date</th>
                    <th>order_amount</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>


The code above contains the HTML parts I just mentioned. The first line creates a heading for the page and the rest creates a table with hard coded column names in the table header.  

Now what I want to do is query my sales_order table and create a table row in the table's body for every record which gets returned. But to do so, first I must establish a connection between the PHP file and the database.
To do so, I used the 'mysql_connect()' function as my database is a MySQL database and embedded this code between the table body element tags.

        <h3 align="center">Sales Order</h3>
        <table border="1" style="width: 100%" align="center">
            <thead style="background-color: #000033; color: #FFFFFF" >
                <tr>
                    <th>order_number</th>
                    <th>customer_number</th>
                    <th>product_code</th>
                    <th>order_date</th>
                    <th>entry_date</th>
                    <th>order_amount</th>
                </tr>
            </thead>
            <tbody>
                <?php
                // Make a MySQL Connection
                mysql_connect("localhost", "root", "MySQLAdmin") or die(mysql_error());
                //Set the schema which contains the table/s required
                mysql_select_db("source") or die(mysql_error());
                ?>
            </tbody>
        </table>

As you can see, I wrapped the PHP code in the <?PHP?> tag and placed it within the table body element tags.
The first line creates a connection to the database via the parameters I passed. These represent the; location of the database, the user name and the password of the MySQL database.
The second line simply specifies the name of the database schema I want to use.

The next step consists of executing a query, looping through the result and creating a row containing the data:

        <h3 align="center">Sales Order</h3>
        <table border="1" style="width: 100%" align="center">
            <thead style="background-color: #000033; color: #FFFFFF" >
                <tr>
                    <th>order_number</th>
                    <th>customer_number</th>
                    <th>product_code</th>
                    <th>order_date</th>
                    <th>entry_date</th>
                    <th>order_amount</th>
                </tr>
            </thead>
            <tbody>
                <?php
                // Make a MySQL Connection
                mysql_connect("localhost", "root", "MySQLAdmin") or die(mysql_error());
                //Set the schema which contains the table/s required
                mysql_select_db("source") or die(mysql_error());
                // Retrieve all the data from the "sales_order" table
                $result = mysql_query("SELECT * FROM sales_order") or die(mysql_error());
                //loop through all the returned records and create a table row for each
                while($row = mysql_fetch_array($result, MYSQLI_ASSOC)){
                    //Use the echo to output HTML code with the retrieved data
                    echo "<tr>";
                    echo "<td align=\"center\">".$row['order_number']."</td>";
                    echo "<td align=\"center\">".$row['customer_number']."</td>";
                    echo "<td align=\"center\">".$row['product_code']."</td>";
                    echo "<td align=\"center\">".$row['order_date']."</td>";
                    echo "<td align=\"center\">".$row['entry_date']."</td>";
                    echo "<td align=\"center\">".$row['order_amount']."</td>";
                    echo "</tr>";
                }
                ?>
            </tbody>
        </table>

To execute a query I used the 'mysql_query()' function and passed the SQL as a parameter. The second part of that line 'or die(mysql_error())' is an error handler.

After retrieving the table's data I used a while loop with the 'mysql_fetch_array()'. If no more records are available in the query result, this method returns 'False' and therefore stops the iteration. Else returns an array representation of a single row, which I store in '$row'.

Within this loop I used the echo to output the HTML code as strings and concatenated the values in '$row' in order to display the data.

Below is the result of my code:



Possible Improvements
Up to now my PHP script dynamically generates the table rows and populates them with the queried data. This is all well and good, but what if I add a previous page which contains a form? This would enable the user to filter out the returned data, thus creating user interaction!
I might implement this if I have the time and post about how I did it, but for this post, that's it for today :)


Hope you found it interesting and I will be posting some updates I did to the paper toss application I mentioned in earlier posts.

1 April 2012

CMT3313 - Week 6 Post - Some Server-Side Technologies

Host Servers
In this post I am going to write a bit about the server-side use of the following web technologies, therefore I will not be getting into much detail on every subject:

  • HTTP
  • Cookies
  • JSP





HTTP at the server side
If you read my very first blog post, you will remember that I wrote:

"Web clients (such as Web Browsers) and Web Servers communicate together via HTTP requests & responses and in order to do this, both must abide to the rules stated in this protocol"

This means that HTTP is not an actual server-side technology, but a protocol which dictates how communication takes place between clients and servers. 

But how is this protocol enforced and where?

The answer to this question is, HTTP is enforced on both sides of the communication channel via the client's web browser and the server's hosting application. Now, ever one of you know what a web browser is, if not you wouldn't be viewing this blog, but what about this server-side hosting application? Well it's actually called a Web Server and there are multiple different brands of it. The first two that come to mind and probably the most popular are Apache HTTP Server and Microsoft's IIS (Internet Information Sever).

These web servers listen out for HTTP requests, locate the requested information and reply back to the requesting client via an HTTP response. The diagram below illustrates this process.
HTTP Request / Response cycle
Keep in mind that this is a very simplified definition on what web servers do, to know more about this topic visit this article at the HowStuffWorks website.

Cookies
The importance of HTTP cookies
No...not the kind you're thinking about! These cookies are not edible unfortunately, but they are very important building blocks of the internet.
Cookies are small files, stored on the client's machine and are used to store some information about the client, in order for the web server to produce and return a web page tailored for a particular user. 

But why does it have to be this way?

Well the reason is, HTTP is stateless, meaning the web server cannot identify a client from the HTTP request it receives, therefore if a client machine sends a request to the web server and after receiving the response, sends another request, the web server has no idea that the second request is from the same client. This limitation would make it quite difficult for you to log into you personal Gmail account or any other internet account for example. The Internet would also loose that certain experience attributed to personalisations as it would not know who you are.

This is where cookies come in handy, as web developers can assign a number for example to every user that visits a site and store it in a cookie on the user's machine. This cookie is then sent with the client's HTTP request and the web server uses it to identify that client.

JSP (Java Server Pages)
JSP is a server-side technology which was first released in June 1999 by the JSP group which was led by Larry Cable and Eduardo Pelegri-Llopart, for more history on JSP visit raible designs.


JSP enables dynamic creation of web pages by embedding Java code in; HTML, XML, DHTML and other file types. What basically happens is, when a client sends an HTTP request to the web server the Java code stored in lets say an HTML file gets executed on the server which generates HTML code according to some passed parameters or query result and returns it to the client machine. 


What If?
As you might already know, many non-technical internet users think that cookies is some sort of malicious software trying to steel their personal information and identity. This is obviously not the case, but this fear might erupt from the fact that the information which identifies the user is sent to the web server along with the HTTP request.
So I was thinking, if JavaScript works on the client side and cookies are stored on the client side as well, one could possibly eliminate or drastically reduce the sending of cookie files to the web server, as their data could be accessed by JavaScript and use AJAX technology to retrieve stored data from the server.
This way cookie files will remain always on the client side and end the myth among non-technical people that cookies are a bad thing.