The PHP Hypertext Pre
The PHP Hypertext Pre
The PHP Hypertext Pre-processor (PHP) is a programming language that allows web
developers to create dynamic content that interacts with databases. PHP is basically used
for developing web based software applications.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server
PHP is a powerful server-side scripting language for creating dynamic and interactive
websites.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's
ASP. PHP is perfectly suited for Web development and can be embedded directly into the
HTML code.
PHP file
A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file are
executed on the server.
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ".php"
What You Should Already Know
Before you continue you should have a basic understanding of the following:
HTML / XHTML
Some scripting knowledge
Where to Start?
Install an Apache server on a Windows or Linux machine
PHP - Echo
As you saw in the previous lesson, the PHP function echo is a means of outputting text to
the web browser. Throughout your PHP career you will be using the echo function more
than any other
Example One
<html>
<head>
<title>First Example<title>
<body>
<?php
Within a document you can embed PHP start and end tags and code at many
points, consider the following example:
<?php
echo '<p>This is PHP script generated.</p>';
?>
<p>This is not.</p>
<?php
PHP - Variables
Variables can be thought of as containers which hold data. The data held by
a variable can change during the execution of a PHP script, hence the name
variable.
A variable is a means of storing a value, such as text string "Hello World!"
or the integer value 4.
Variables in PHP are represented by a $ symbol followed by the name of
the variable.
$var_name = value;
$name = Simon;
NB: PHP variable names are case sensitive. Therefore the variable $name is a different
variable to $Name. Be careful!
PHP Variable Naming Conventions
There are a set of rules which need to be considered in naming your variables.
A valid variable name can start with a letter or an underscore character, followed by any
number of letters, numbers or underscores
Strings
A string is a series of characters. We have used strings in our previous PHP examples but
it is now time to explain that PHP has three different ways in which strings can be
specified.
<?php
$strName = 'Elizabeth';
echo '<p>';
echo $strName;
echo '</p>';
?>
String Operators
PHP supports two string operators.
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
$Named = "Elizabeth";
$age=45;
echo "My name is ". $Named. " and I'm ".$age." old";
?>
</body>
</html>
</body>
</html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
$strNamed = "Elizabeth";
$intage=45;
echo "My name is ". $strNamed. " and I'm ".$intage." old";
?>
</body>
</html>
</body>
</html>
<?php
$strFirstname = "Simon";
$strSurname = "Stobart";
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
<?php
$intA = 5;
$intB = 3;
if ($intA > $intB)
echo "<p>$intA is greater than $intB</p>";
?>
<?php
$strColour = "green";
if ($strColour == "green")
echo "<p>The colour is green</p>";
if ($strColour == "green")
echo "<p>Green is a nice colour</p>";
if ($strColour == "green")
echo "<p>We have the colour of grass</p>";
?>
Brace characters may be used to ({ }) to group all statements that you wish to
conditionally execute into a statement group, for example:
<?php
$strColour = "green";
if ($strColour == "green") {
echo "<p>The colour is green</p>";
echo "<p>Green is a nice colour</p>";
echo "<p>We have the colour of grass</p>";
}
?>
Braces can be formatted so that they appear like the example above:
If ( expression ) {
}
Alternatively they can appear on separate lines:
If ( expression )
{
elseif ( expression )
statement to be executed if elseif condition is true
else
<?php
$intNumber1 = 100;
$intNumber2 = 80;
if ($intNumber1 > $intNumber2)
{
echo "<p>$intNumber1 is larger than $intNumber2</p>";
}
elseif ($intNumber1 == $intNumber2)
{
echo "<p>$intNumber1 is equal to $intNumber2</p>";
}
else
{
echo "<p>$intNumber1 is smaller than $intNumber2</p>";
}
?>
switch construct
The switch construct is similar to a series of if statements acting on the same conditional
expression. The switch construct is used when you wish to compare a variable against a
number of different values and execute different code statements depending on the
variables value.
The case construct consists of a switch component in which an expression is evaluated.
The result of the expression is then compared in turn to a list of case statements. The first
case value which matches to the expression will determine which associated statements
are executed
The syntax of the switch statement is:
switch ( expression )
{
case constant expression : statement
case constant expression : statement
...
default : statement
}
<?php
$strName = "Elizabeth";
switch ($strName) {
case "Simon":
echo "<p>Hello Simon</p>";
case "Elizabeth":
<?php
$intTotal = 3;
switch ($intTotal)
{
case 0:
case 1:
case 2:
case 3:
case 4:
echo "<p>$intTotal is less than or equal to four!</p>";
break;
case 5:
echo "<p>$intTotal is greater than four!</p>";
}
?>
<?php
$intTotal = 6;
switch ($intTotal) {
case 0:
case 1:
case 2:
case 3:
case 4:
echo "<p>$intTotal is less than or equal to four!</p>";
break;
case 5:
echo "<p>$intTotal is equal to five!</p>";
break;
default:
echo "<p>$intTotal is greater than five!</p>";
}
?>
PHP Loops
While loops
while ( expression )
{
statement
}
<?php
$intCount = 1;
while ($intCount <= 10)
{
echo "<p>Iteration $intCount</p>";
$intCount++;
}
?>
Do while loops
do
{
statement
statement
}
while ( expression );
<?php
$intCount = 1;
Do
{
echo "<p>Iteration $intCount</p>";
$intCount++;
} while ($intCount <= 10);
?>
<?php
$intCount = 1;
Do
{
echo "<p>Iteration $intCount</p>";
$intCount++;
} while ($intCount < 1);
?>
For loop
There are three expressions incorporated into the for construct.
The syntax for the loop is:
for (expression; expression; expression)
{
statement
statement
}
<?php
for($intCount = 1; $intCount <= 10; $intCount++)
echo "<p>Iteration $intCount</p>";
?>
foreach loop
PHP supports a special loop construct for accessing the contents of arrays
Used in Array Examples
Arrays
An array in PHP is actually an ordered map, where a map is a type which maps values to
keys. Because PHP stores its arrays as maps it means that they can be used for a whole
variety of different data structures such as lists, trees, stacks etc. Arrays are used to
collect together data, such as peoples names and perform operations on this data as
easily as possible. PHP supports both single and multi-dimensional arrays, but for now
lets look at creating a very simple array.
Arrays are created using the array construct:
theArray = array (arrayItem1, arrayItem2, );
Example
$arrColours = array (Red, Green, Blue, Yellow, White);
This creates an array called $arrColours which contains 5 elements storing various
colours. We can refer to the elements within the array by using a subscript to the array
name. Because the index defaults to numbering the array index from 0 to in this case to 4
then we can access the first element of the array by the following statement:
$arrColours[0];
and the last element of the array by:
$arrColours[4];
Example
<?php
$arrColours = array ("Red", "Green", "Blue", "Yellow", "White");
for($intCount=0;$intCount<5;$intCount++)
echo "<p>" . $arrColours[$intCount] . "</p>";
?>
Array Output
In the above example the index has not been created in numerical order and in addition a
blank index key, number 5 has been included. If we use the above array with a slightly
modified version of our simple for loop example before we can see what is displayed
when we cycle through the array:
<?php
$arrColours = array (0=>"Red", 2=>"Green", 3=>"Blue", 5=>"", 1=>"Yellow",
4=>"White");
for($intCount=0;$intCount<6;$intCount++)
echo "<p>$intCount " . $arrColours[$intCount] . "</p>";
?>
Foreach
PHP includes a loop construct specifically designed for iterating through arrays. This
loop construct is known as the foreach loop and there are two syntaxes. The first form is:
foreach (array as value) statement
The foreach loop will iterate through the array provided by array. The value in the current
index is assigned to value. The array index is then incremented by one so the next
iteration of the loop will access the next element of the array. An example of this loop has
been included in the following script that is a rewrite of the previous one:
<?php
$arrColours = array (0=>"Red", 2=>"Green", 3=>"Blue", 5=>"", 1=>"Yellow",
4=>"White");
$intCount = 0;
foreach($arrColours as $strColour)
echo "<p>" . $intCount++ . " $strColour</p>";
?>
Note that the output of the colours is also in the order in which they were declared,
not in the numerical index order, as with the for loop.
This foreach statement is similar to the previous example but in addition assigns the value
of the current elements index to the key. This is shown in the following script:
<?php
$arrColours = array (0=>"Red", 2=>"Green", 3=>"Blue", 5=>"", 1=>"Yellow",
4=>"White");
foreach($arrColours as $intKey=>$strColour)
echo "<p>$intKey $strColour</p>";
?>
PHP Functions
The real power of PHP comes from its functions.
In PHP - there are more than 700 built-in functions available.
Create a PHP Function
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
function functioname()
{
Code to be executed
}
<html>
<body>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
writeMyName();
?>
</body>
</html>
To add more functionality to a function, we can add parameters. The parameters are
specified inside the parentheses.
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeMyName("Kai Jim");
echo "My name is ";
writeMyName("Hege");
echo "My name is ";
writeMyName("Stale");
?>
</body>
</html>
The output of the code above will be:
<html>
<body>
<?php
function writeMyName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeMyName("Kai Jim",".");
echo "My name is ";
writeMyName("Hege","!");
echo "My name is ";
writeMyName("Stle","...");
?>
</body>
</html>
Example
<html>
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16)
?>
</body>
</html>
Example
Note: When using the $_GET variable all variable names and values are displayed in the
URL. So this method should not be used when sending passwords or other sensitive
information.
Note: The HTTP GET method is not suitable on large variable values; the value cannot
exceed 100 characters.
PHP $_POST
The $_POST variable is used to collect values from a form with method="post".
The $_POST variable is an array of variable names and values sent by the HTTP POST
method.
The $_POST variable is used to collect values from a form with method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
Note: Variables sent with HTTP POST are not shown in the URL
Note: Variables have no length limit
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with
both the GET and POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years old!
Accessing form data is essentially very easy. When a form is created an associated array
of variables is created. This array is called $_POST. Each HTML form element that has a
unique name is stored in the array and can be accessed by the PHP script. The $_POST
syntax is as follows:
$_POST["name"];
name is the name of the form value we wish to access. In our example we have assigned
the contents of each of our form fields into variables of the same name:
$strFirstname = $_POST["strFirstname"];
$strSurname = $_POST["strSurname"];
$strUsername = $_POST["strUsername"];
$strPassword = $_POST["strPassword"];
The values of these variables are then finally displayed using a couple of echo
statements.
The example2 HTML page below contains several input fields and a submit button. When the user
fills in this form and click on the submit button, the form data is sent to the "example1.php" file.
<HTML>
<BODY>
<h2>Please enter your personal details:</h2>
<form action="example1.php" method="post">
Firstname<input type="text" name="strFirstname"/><BR>
Surname<input type="text" name="strSurname" /><BR>
Username<input type="text" name="strUsername" /><BR>
Password<input type="password" name="strPassword"
/><BR>
<input type="submit"/>
</p>
</form>
</BODY>
</HTML>
<HTML>
<BODY>
<?php
$strFirstname = $_POST["strFirstname"];
$strSurname = $_POST["strSurname"];
$strUsername = $_POST["strUsername"];
$strPassword = $_POST["strPassword"];
echo "<p>Greetings $strFirstname $strSurname</p>";
echo "<p>Your username is $strUsername and your password
is $strPassword</p>";
?>
</HTML>
</BODY>
<HTML>
<BODY>
<h2>Please enter your personal details:</h2>
<form action='example6.php' method='post'>
<p>
<label for="strFirstname">Firstname: </label>
What is MySQL?
MySQL is a database. A database defines a structure for storing information.
Relational Database
In relational database systems such as MySQL data is organized into tables
Database Tables
A database most often contains one or more tables. Each table has a name (e.g.
"Customers" or "Orders"). Each table contains records (rows) with dat
We see that it contains a table called Customers. This table consists of three column fields of
data entitled Title, Surname and Firstname. The data is inserted into each of these fields
forming a number of record rows within the table.
Queries
Database queries
A query is a question or a request.
With MySQL, we can query a database for specific information and have a recordset
returned.
Connecting to a MySQL DBMS
PHP MySQL Connect to a Database
The free MySQL Database is very often used with PHP
Connecting to a MySQL DBMS
In order for a PHP script to access a database we need to form a connection from the script to
the database management system (DBMS). To do this we use the mysql_connect() function
mysql_connect(servername,username,password);
The mysql_connect() function requires three parameters. The first is the name of the server,
the second is your username and the third your password.
If you are developing on your own standalone computer the format of this function may
look like this with the value of server set to be localhost, the username as root and
whatever password you have set:
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
The above script opens a connection to the DBMS server and then attempts to select
database glassesrus.
Reading a Database
The next step in linking PHP to a database is to get it to send a Structured Query
Language (SQL) statement to the database in order to begin to retrieve data records.
To do this we need to introduce a new function that of mysql_query()
resourceRecords mysql_query (query, resourceId);
Function mysql_query() requires two parameters, the first is an SQL query string and the
second is the database resource identifier returned from the mysql_connect() function.
Example
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
Adding this function into our script gives us.
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
Now the mysql_query() function returns us a resource pointer to all the records which
match the SQL statement we supplied. This could be zero, one or many records. What we
need is a function which will return the contents of one record cell from the record set.
This function is called mysql_result():
fielddata mysql_result (resourceRecords, row, field);
The mysql_query() function requires three parameters. The first is the resource pointer to
the records returned by the mysql_query() function. The second is the number
indicating which record to return, with 0 being the first record, 1 the second and so on.
The third parameter is the name of the database field to return. The function returns the
data stored in the field. Here is an example of the function:
$strSurname = mysql_result($dbRecords, 0, surname);
Adding this function into our script gives us.
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
$strSurname = mysql_result($dbRecords, 0, "Surname");
echo "<p>$strSurname</p>";
?>
The function requires a single parameter which is the resource identifier returned from
the mysql_result() function. It returns an array containing the database record. When
this new function is combined with a loop construct we can access and display all of the
records returned.
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrRecord = mysql_fetch_row($dbRecords))
{
echo "<p>" . $arrRecord[0] . " ";
echo $arrRecord[1] . " ";
echo $arrRecord[2] . " ";
echo $arrRecord[3] . "</p>";
}
?>
This function returns a single database record and stores this in the array $arrRecord.
When the last record has been returned mysql_fetch_row() returns false and the loop
will stop iterating.
Within the loop a number of echo statements are used to display the fields. The fields are
stored within the $arrRecord array and are accessed through each array element, 0, 1, 2
and 3.
mysql_fetch_array()
The function mysql_fetch_array() is an extended version of function mysql_fetch_row():
Like the mysql_fetch_row() function the mysql_fetch_array() function requires a single
parameter which is the resource identifier returned from the mysql_result() function. It
returns an array containing the database record.
The one thing that does differ from the mysql_fetch_row() function is that we can refer to
the database fields by name.
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
{
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords["Title"] . " ";
echo $arrRecords["Surname"] . " ";
echo $arrRecords["Firstname"] . "</p>";
}
?>
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbProdRecords = mysql_query("INSERT INTO products VALUES ('', 'Beer
Mug', '600 ml Beer Mug', '100', '5.99')", $dbLocalhost)
or die("Problem writing to table: " . mysql_error());
?>
The above script invokes a mysql_query() function with the SQL statement:
INSERT INTO products VALUES ('', 'Beer Mug', '600 ml Beer Mug', '100', '5.99')
This SQL statement creates a new data record in the products table.
Deleting Records
We can delete records from tables using the mysql_query() function using the DELETE
FROM query:
DELETE FROM table WHERE field=value
The DELETE FROM query requires the name of the database table to be provided as
well as the field and its value which we are looking to delete.
DELETE FROM customers WHERE Id='3'
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbCustRecords = mysql_query("DELETE FROM customers WHERE Id='3'",
$dbLocalhost)
or die("Problem writing to table: " . mysql_error());
?>
Amending Records
The SQL UPDATE query can be used to modify the contents of an existing database
record.