Web Applications With Php And Mysql

PHP

Installing PHP on Ubuntu Linux

Installing PHP on Ubuntu Linux was simple

sudo apt-get install php5

Installing Apache2 on Ubuntu

sudo apt-get install apache2

Introduction

PHP is a backend scripting language for web applications. What this means is, you can put PHP code in HTML files (by inserting it in a special syntax). When the server is about to serve the files, it will actually execute the php code in a PHP interpretor, before sending it to the client browser.

There are three ways of embedding php code in an HTML file.

@@

<?php 
echo '<b>hello world</a>';
?>

<script language="php">
echo '<b>hello world</a>';
</script>

<?
echo '<b>hello world</a>';
/*For the above style to work, you will have to include the 
'short_open_tag' setting in PHP's configuration file.*/
?>

<%
echo '<b>hello world</a>';
//For this style to work, you will have to include the 'asp_tags' setting in PHP's configuration file.
%>

@@

The examples above uses just a simple echo statement, but essentially you can the PHP interpretor what to do by including any valid PHP statement(s) between the beginning and ending tags.

Like most programming languages, PHP also makes use of semi-colons to end statements.

Comments in PHP are similar to most C style languages.

The PHP interpretor ignores whitespaces, and newlines.

Till now we have not done anything which cannot be done with HTML. Let us invoke a PHP function from out code.

@@

<?php
  echo '<b>Hello</b> the time right now is '.date('H:i, jS F');
?>

@@

In the example above, the period (.) operator is used to concatenate Strings.

The date() function expects the argument you pass it to be a format string, representing the style of output you would like. Each letter in the string represents one part of the date and time. H is the hour in a 24-hour format with leading zeros where required, i is the minutes with a leading zero where required, j is the day of the month without a leading zero, S represents the ordinal suffix (in this case th), and F is the full name of the month.

Note: PHP has used a very strange choice of letters for formatting dates. It is so much easier to remember 'm' for minutes, and 'd' for day. Not sure why they chose 'i' and 'j' instead.

Form processing with PHP

Let's now look at an example which is closer to web applications. Almost all web applications need to do input processing. In this example we will display a simple form to a user asking for their name. When the form is submitted (to a PHP script) it will display hello with the user's name.

Let's first look at the HTML page containing the form.

@@

<form method="POST" action="hellosubmit.php">
  <input type="text" name="username" />
  <input type="submit" name="submit" value="submit" />
</form>

@@

And the page which processes the form.

@@

<?php
    echo 'Hello '.$_POST['username'];
?>

@@

This page receives the data input by the user. In PHP Form data can be retrieved from the $_POST array if the method was POST, and $_GET if it was a GET request. Regardless of the method, the data will always be available in $_REQUEST array.

There are two more ways in which we can access form data.
$username
$HTTP_POST_VARS['username']

The first style poses a security risk because any value the user provides (by way of request parameters) will be set in global variables by that name. If a PHP script does not specify an initial value for a certain variable, then an errant user could set a request parameter which will populate that variable (with mischievous data).

The second style is also not recommended because it has been deprecated, so may not be supported in future versions of PHP.

Notice the co-relation between the name of the form field and the name of the variable (or the array subscript).

The code we showed above, can also be written as:

@@

<?php
    echo 'Hello '.$_POST['username'].'<br/>';
    $username = $_POST['username'];
    echo "Hi there $username";
?>

@@

In the line below, we embed a variable inside a String. This is known as String interpolation.

echo "Hi there $username";

String interpolation is allowed only with Strings created with double quotes and with multi-line Strings. Multi line Strings are shown in the line below.

@@

$word = "interpolation";

<?php
echo «<mark
This is a multi line
String. These String also support $word
mark
?>
[[/code]]

@@

Data types in PHP

PHP supports the following data types:

  • Integer
  • Float (aka Double)
  • Boolean
  • String
  • Array
  • Object
  • NULL (used for variables whose values are not initialized)
  • resource (used to denote an external resource such as a database connection)

Typecasting from one type to another type is possible, though I am not sure if we can typecast the String "1" to the number 1. Will have to check.

PHP has a special type called variable valriable. This is used to refer to variables when their names are not known as code time, and will be known only at runtime. This allows some degree of meta-programing (I think to the extent of reflection in Java)

We can also define constants in PHP using the following syntax:
define('MAX_SEATS', 75);
After defining MAX_SEATS, we can use the constant like any variable, but without the $ sign
WRONG - $MAX_SEATS
RIGHT - MAX_SEATS

Constants cannot store Arrays or Objects. They are restricted to Boolean, Integer, String, and Float data.

Running the inbuilt function phpinfo() will provide us a list of all the constants and variables set by PHP.

Scoping rules

Scoping rules refers to the visibility of variables. PHP has 6 type of variables.

  1. Superglobals - These variables are visible from everywhere
  2. Constants - Once declared, they are visible globally (inside and outside of functions). What is the difference between superglobals and globals?
  3. Variables inside functions can be declared as global, and they refer to global variables of the same name (Need to better understand this)
  4. Variables declared inside functions can be declared as static. They are not visible outside of the function, but they keep their values even after the function invocation.
  5. Variables declared inside functions are local and do not exist after the function exits (these are put on the stack)

This is the list of superglobals:

$GLOBALS — An array of all global variables (Like the global keyword, this allows
you to access global variables inside a function—for example, as
$GLOBALS[‘ myvariable’ ] .)

$_SERVER—An array of server environment variables

$_GET—An array of variables passed to the script via the GET method

$_POST—An array of variables passed to the script via the POST method

$_COOKIE—An array of cookie variables

$_FILES—An array of variables related to file uploads

$_ENV—An array of environment variables

$_REQUEST—An array of all user input including the contents of input including

$_GET, $_POST, and $_COOKIE (but not including $_FILES since PHP 4.3.0)

$_SESSION—An array of session variables

Operators in PHP

Arithmetic operators are what I expected (+, -, *, /, %) If we try to apply arithmetic operators on a String, PHP will try to convert the String to a number. There are certain rules that govern this conversion.

The period '.' is the sole String operator, which is used for concatenation.

The assignment operator returns the value it assigns, making it possible to write statements like this.

$b = 6 + ($a = 5) ;

In PHP an assignment results in a separate copy being made. So the following code will result the value of $a being copied in a separate memory location, which is assigned to $b.

$a = 4;
$b = $a;

However, we can also use references if we want both to point to the same memory location.

$b = &$a;

If required, later we can unset a reference, and PHP will again resort to copying the value.

unset($b);

Comparison operators in PHP are similar to what I would have expected. PHP also has the notion of truthy and falsy values. Any non zero value evaluates to true, while zero values evaluate to false.

One operator to note is the '===' operator. This will return true only if both values are equal and of the same type. Basically this operator will return false if a type conversion needs to be made.

$a = 0;
$b = "0";
$a == $b; //true
$a === $b; //false

Just like '!=', '<>' is also a not equal operator.

Logical operators in PHP are again what I would expect. '&&' as well as 'and'are available.

PHP has all the bitwise operators I expected.
& and
| or
~ not
^ xor
« left shift

right shift

PHP supports the regular ternary operator (condition ? eval1 : eval2;)

PHP has an error suppression operator '@'.

$a = @(70/0); //this statement would have resulted in a divide by zero warning had we not used the error suppression operator.

If we do use this operator, we may want to still keep a tab on the errors that are generated. If PHP has been setup with $track_errors feature in php.ini, then the errors will be available in $php_errormsg global variable.

PHP also has an execution operator `cmd`, using which we can run commands on the server, and print their outputs or do something useful with them.

Elements of an array can be accessed either using [] with a subscript, or the => operator (in some cases only). Most operators are overloaded in the context of arrays as follows:
\+ concatenates two arrays
== Both arrays have the same key and pairs
=== Both arrays have the same key and pairs and order
!= (and <>) inequality
!== not identity

PHP also has an instanceof operator to verify the type of a variable.

Variable functions

Variable functions work on variables. They are used to get/set the type of variables. They are also used to perform tests (usually type or capability related) on variables.

string gettype(mixed var); Returns one of bool, int, double (for floats), string, array, object, resource, NULL
bool settype(mixed var, string type)

is_array(v)
is_float(v), is_real(v), is_double(v)
is_integer(v), is_long(v), is_int(v)
is_callable(v)
is_string(v)
is_bool(v)
is_resource(v)
is_scalar(v)
is_object(v)
is_null(v)
is_numeric(v)

isset(mixed var); //tells us if a variable has been set
unset(mixed var); //gets rid of the variable

Question: What will happen if we unset a global variable?

empty(v); //returns true if this variable exists and has a non empty value

PHP also has three functions for being able to do type casting by calling functions.

int intval(mixed var)
float floatval(mixed var)
string strval(mixed var)

Note: I believe this is very similar to the settype function already discussed before. This is possibly simpler.

conditionals in PHP

PHP has if … else … elseif just as expected

PHP also has a switch statement. The expression in switch must evaluate to either int, float, or string. Rest is similar to Java.

PHP also has a while() {} and for(expr1;cond;expr2){}

PHP also has a for…each loop which is used with arrays.

The continue and break statements work as expected in PHP. The exit statement will send control out of the script.

Processing files in PHP

I am skipping over this part for the time being. Will return to it shortly.

User defined functions in PHP

This is a simple function definition in PHP.

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}
?>

Functions can also be defined inside other functions. A function need not be defined before it is referenced, unless it is defined conditionally. Functions can be defined with fixed as well as variable number of arguments.

Arguments can be given default values, as shown below (as one would expect the arguments with default values must be declared on the right of ones that don't). Default arguments can either be scalar or non-scalar arguments.

function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}

By default function arguments are passed by value. To pass by reference use:

function makecoffee(&$type)
{
    return "Making a cup of $type.\n";
}

MySql

Installation

I installed MySql on Ubuntu 10.04 using the Synaptic Package Manager (GUI tool). I installed mysql-server-5.1 and mysql-client-5.1 .

Creating a database, and table

Here is a small YOUTube video I made which shows how to create the database and table.

In this video, I show how to insert data into the table.

Data Relationships

For this assignment, I first added a column for authors to the books table. The video below shows how I did it.

In the above video I show how to add a column to an existing table using the following SQL statement.

alter table books add column author varchar(100);

Question: How will we represent data when there are multiple authors for a book. Remember that we can do it with the above design, but there is a problem. What is it?

Answer: Since we have an author column in the table, we can intuitively store only 1 author. The table will look like this when we store one author for a book.

ISBN - TITLE - AUTHOR
12345 - Thinking In Java - Brue Eckel

However, if we were to add a book with multiple authors, then we are restricted to representing multiple authors in the same column.

ISBN - TITLE - AUTHOR
12345 - Thinking In Java - Brue Eckel
23456 - Head First Java - Kathy Sierra, Bert Bates

THIS IS BAD on multiple counts. This excellent explanation of normalization by Phillip Greenspun, explains why it is bad:

  1. The combination of table name, column name, and ID will not identify one datum
  2. We may not have enough space in the column if we have say 1000 authors for one book (also imagine how will you create a query which will list all books written by an author and even if we could write it, how inefficient it would be.)
  3. It would be difficult to impossible to manipulate multi-valued columns with basic INSERT, DELETE, UPDATE operations.
  4. The design will just become way too warped

For all these reasons we should not use a column which will hold multiple values (such as two author names).

Question: An author may have written multiple books. Do you think our current design wastes space? Why?
Answer: If an author has written multiple books, their name will be repeated in the 'author' column for every book row. This is a waste of space.

What we should do is to create another table for authors. But first let us remove the 'author' column from the table.

The video below shows how to drop a column from a database table.

In the video above we saw how to drop a database table column using the following SQL.

alter table books drop column author;

Create a table for authors

We saw in the previous section that using a row for authors in the book table is not a good idea. What we need is a separate table for authors.

CREATE table authors (
    id INT PRIMARY KEY, 
    book VARCHAR(13) NOT NULL, 
    first_name varchar(256), 
    middle_initial varchar(256), 
    last_name varchar(256) NOT NULL, 
    FOREIGN KEY (book) REFERENCES book(isbn));

This will create a table 'authors' which has a FOREIGN KEY relationship with the table 'books'. The tables authors and books are connected by having the same value in the column authors.book and book.isbn.

Now let's add some authors to the authors table.

insert into authors (id, book, first_name, last_name) values (1, '52345', 'Phillip', 'Greenspun');
insert into authors (id, book, first_name, last_name) values (1, '52345', 'Alex', 'Z');

Now let is issue a simple query, which will list the books with their authors.

select books.title, books.isbn, authors.first_name, authors.middle_initial, authors.last_name from books, authors where authors.book = books.isbn;

The same query can also be written with the join keyword.

select books.title, books.isbn, authors.first_name, authors.middle_initial, authors.last_name from books join authors on (authors.book = books.isbn);

Advanced PHP

Real World Project