Lecture 1: Introduction To PHP - Part I: Integrative Programming Lectures & Practice Exercises
Lecture 1: Introduction To PHP - Part I: Integrative Programming Lectures & Practice Exercises
Lecture 1: Introduction To PHP - Part I: Integrative Programming Lectures & Practice Exercises
What is PHP?
PHP originally meant “Personal Home Page” as it was created in 1994 by Rasmus Lerdorf to track the visitors to his
online resume.
As its usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean
“PHP: Hypertext Preprocessor.”
Using gmdate(): Open first.php and add this line after the last print:
<html> <head> <title> PHP Test: First Example </title> </head>
<body>
<?php
print "Hello World!<br>";
print "I'm in <b>RTU!</b><br>";
echo 'She said, "How are you?"<br>';
print "I'm just fine.<br>";
print "Today’s date is ";
echo gmdate("M d Y");
?>
</body>
<html>
Output of “first.php”:
Writing Comments
Integrative Programming Page 3 of 19
Lectures & Practice Exercises
PHP supports three comment types. First is similar to comments in shell scripts (from Unix) and uses the pound or
number symbol(#). The second stems from the C++ programming language. The third comment style—arising from
C—allows for comments to run over multiple lines. Examples, respectively:
# This is comment.
// This is also a comment.
/* This is a larger comment
that spans two lines. */
Using Variables
Variables are widgets used to temporarily store values. These values can be numbers, text, or much more complex
arrangements. There are eight types of variables in the PHP language. These include four-scalar (single-valued)
types—Boolean (TRUE or FALSE), integer, floating point (decimals), and strings (text): two non-scalar (multi-valued)
—arrays and objects; plus resources. All variables in PHP follow certain syntactical rules:
o A variable’s name must start with a dollar sign ($), for example, $name.
o The name can contain a combination of strings, numbers, and the underscore, example, $my_report.
o The first character after the dollar sign cannot be a number (it must be either a letter or an underscore).
o Variable names in PHP are case-sensitive. So $name and $Name are entirely different variables.
o Variables can be assigned values using the equals sign (=).
STRINGS: A string is merely a quoted chunk of letters, numbers, spaces, punctuation, etc. Below are examples of
assigning a string value to variables and printing out their values.
Concatenating Strings: Concatenation is addition for strings and is performed using the period (.). If assigning
another value to an existing variable, say ($book), the new value will overwrite the old one. If concatenating one
value to another, the concatenation assignment operator (.=) is used.
STRINGS: PHP has a slew of useful string-specific functions:
o strlen() – returns a number how long a string is (characters it contain).
o strtolower() – returns a string converted entirely into lowercase characters.
o strtoupper() – returns a string converted entirely into uppercase characters.
o ucwords() – capitalizes the first character of every word.
Second Example: Open text editor and type the code below. Save it as “variables.php”.
<html> <head> <title> PHP Test: Variables </title> </head>
<body bgcolor=black> <font color=white>
<?php
echo "<b>Using String Variables</b><br>";
print "Today’s date is ";
echo gmdate("M d Y");
echo "<br>";
NUMBERS: PHP has both integer and floating-point (decimal) number types. Some number functions are
round()are number_format(). Example:
$n = 3.14;
$n = round($n); //3 or to a specified number of decimal places
$n = 3.142857;
$n = round ($n, 3); //3.143
$m = 23000;
$m = number_format($m); //23,000
NUMBERS: Arithmetic Operators:
Operator Meaning
Integrative Programming Page 5 of 19
Lectures & Practice Exercises
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
CONSTANTS: Constants are a specific data type in PHP which unlike variables, retain their initial value throughout
the course of a script. The value of the constant cannot be changed once has it been set. To create a constant, use
the define()function instead of the assignment operator for variables.
ESCAPE CHARACTERS:
Code Meaning
\" Double quotation mark
\' Single quotation mark
\\ Backslash
\n Newline
\r Carriage return
\r Tab
\$ Dollar sign
Single and Double Quotation Marks: In PHP, values enclosed within single quotation marks will be treated
literally, whereas those within double quotation marks will be interpolated. Placing variables and special characters
within double quotes will have their represented values printed, not their literal values.
Third Example: Open text editor and type the code below. Save it as “numbers.php”.
<html> <head> <title> PHP Test: Using Numbers </title> </head>
<body bgcolor=black> <font color=white>
<?php
echo "<b>Using Numbers </b><br>";
print "Today’s date is ";
echo gmdate("M d Y");
echo "<br>";
$quantity = 30; // 30 pcs.
$price = 119.95; // $119.95
$taxrate = .05; // 5% tax rate
$total = $quantity * $price;
$total = $total + ($total * $taxrate); // Add tax
$total = number_format ($total, 2); // Format the results
echo "You are purchasing <b> $quantity </b> widgets at a cost of <b>\$ $price</b>
each.<br>";
echo "With tax, the total comes to <b>\$ $total </b><br><br>";
echo "<b>Using define() Function</b><br>";
define ("YEAR", "2005");
define ("INDAY", "July 4th");
echo "US Independence Day is " . INDAY . "<br>";
echo "We are in year " . YEAR . ".<br>";
echo "This server is running version " . "<b>" . PHP_VERSION . " of the PHP on the "
. PHP_OS . ".</b><br><br>";
echo "<b>Single and Double Quotation Marks</b><br>";
$var = 'test';
echo "var is equal to $var <br>";
echo 'var is equal to $var <br>';
?>
</font>
</body>
</html>
Integrative Programming Page 6 of 19
Lectures & Practice Exercises
LABORATORY EXERCISES:
Create a folder named after your SURNAME under the directory c:/Program Files/Apache
Group/Apache/htdocs/VALDERAMA
Create the following Sample Exercises first:
O FIRST_INITIALSPC# (EX. FIRST_AV60.PHP)
O VARIABLES_INITIALSPC# (EX. VARIABLES_AV60.PHP)
O NUMBERS_INITIALSPC# (EX. NUMBERS_AV60.PHP)
Then solve the exercise below. Save it in just one .PHP file using the filename: EXER01INITIALSPC# (EXAMPLE:
EXER01AV60.PHP)
Write a PHP code that will display the following:
a. complete date and time today;
b. your complete name in all capital letters (using strtoupper() function); and do the FF.:
Display the Area, Circumference, and Diameter of a circle if the radius is 23.
Display the Area of a triangle if the base is 10 and the height is 12.
Display the value in degrees Celsius if the degree in Fahrenheit is 50.
Display the value of 1500 pesos in dollars if the conversion factor is $1 = P54.25
Use the following:
1. Celsius = 5/9 * (Fahrenheit – 32)
2. Diameter = 2 * Radius
3. Circumference = 2 * Pi * Radius
4. Area (circle)= Pi * Radius * Radius
5. Area (triangle) = ½ * Base * Height
Refer to the output below:
Integrative Programming Page 7 of 19
Lectures & Practice Exercises
<html> <head> <title> Use of HTML Form Tags in PHP </title> </head>
<body bgcolor="99ffff">
<?php
echo "OUTPUT From: <b> TextField </b> <br>";
echo "Hi {$_POST['name']}!<br>";
echo "You are {$_POST['age']} years old. <br><br>";
echo "OUTPUT From: <b> Checkbox </b> <br>";
echo "Checkbox status: <b> {$_POST['choice']} </b> <br><br>";
echo "OUTPUT From: <b> Multiple CheckBoxes </b> <br>";
echo "You have experienced: <br>";
echo "  {$_POST['choice1']} <br>";
echo "  {$_POST['choice2']} <br>";
echo "  {$_POST['choice3']} <br><br>";
echo "OUTPUT From: <b> Radio Button </b> <br>";
echo "You selected: {$_POST['q1']} <br><br>";
echo "OUTPUT From: <b> List Box </b> <br>";
echo "Price Range: {$_POST['price']} <br><br>";
echo "<br>Pants Size(s): {$_POST['pantsSize[0]']}";
echo "{$_POST['pantsSize[1]']}";
echo "{$_POST['pantsSize[2]']}";
echo "{$_POST['pantsSize[3]']} <br><br>";
echo "OUTPUT From: <b> TextArea </b> <br>";
echo "{$_POST['w']} <br>";
?>
</body>
</html>
Integrative Programming Page 10 of 19
Lectures & Practice Exercises
OUTPUT:
if ($hotel=="three") {
if ($destination=="HongKong") {
$hotelmodifier = 2;
$price = $price * $placemodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else if ($destination=="Singapore") {
$hotelmodifier = 3.5;
$price = $price * $placemodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else if ($destination=="Malaysia") {
$price = $price * $placemodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else {
echo "Sorry, you have made an invalid entry.";
}
}
else if ($hotel=="five") {
if ($destination=="HongKong") {
$hotelmodifier = 2.5;
$price = $price * $placemodifier * $hotelmodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else if ($destination=="Singapore") {
$hotelmodifier = 4;
$price = $price * $placemodifier * $hotelmodifier;
Integrative Programming Page 12 of 19
Lectures & Practice Exercises
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else if ($destination=="Malaysia") {
$price = $price * $placemodifier * $hotelmodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else {
echo "Sorry, you have made an invalid entry.";
}
}
else {
echo "Sorry, you have made an invalid entry.";
}
?>
</body>
</html>
SAMPLE OUTPUT:
Integrative Programming Page 14 of 19
Lectures & Practice Exercises
Use the database; Show the current tables; and create a new table;
inputform.html
<html>
<head> <title> Sample Input Form </title></head>
<body bgcolor="cc3366" text="ffff99" vlink="ffff99">
<font face="Arial">
<center>
<form action="insertdata.php" method="post">
<table border=0 cellspacing=10>
<tr>
<td> Name: </td>
<td> <input type="text" name="name"> </td>
</tr>
<tr>
<td> Course: </td>
<td> <input type="text" name="course"> </td>
</tr>
<tr>
<td> Gender[F/M]: </td>
<td> <input type="text" name="gender"> </td>
</tr>
<tr>
<td> Email Address: </td>
<td> <input type="text" name="email"> </td>
</tr>
</table>
<input type="submit" name="submit" value="Save Entry">      
<input type="reset" name="reset" value="Clear">      
</form>
<a href="viewrecords.php" onMouseover="window.status='View Records'; return true" onMouseout="window.status=' ';
return true"> View Records </a>    
</html>
insertdata.php
<html>
<head> <title> Insert Data </title>
<body bgcolor=cc3366 text=ffff99 topmargin=100 vlink=ffff99>
<font face="Arial">
<?php
$dbc = mysql_connect ('localhost','root','') OR die ('Could not select the database because: <b>' . mysql_error() .
'</b>');
mysql_select_db('db_students') OR die( 'Could not connect to MySQL because: <b>' . mysql_error() . '</b>');
viewrecords.php
<html> <head> <title> View Records </title></head>
<body bgcolor="cc3366" text="ffff99" vlink="ffff99">
<font face="Arial"> <center>
<?php
$dbc = mysql_connect ('localhost','root','') OR die ('Could not select the database because: <b>' . mysql_error() .
'</b>');
mysql_select_db('db_students') OR die( 'Could not connect to MySQL because: <b>' . mysql_error() . '</b>');
deletedata.php
<html> <head> <title> Delete data </title>
<body bgcolor=cc3366 text=ffff99 topmargin=100 vlink=ffff99>
<font face="Arial">
<?php
$dbc = mysql_connect ('localhost','root','') OR die ('Could not select the database because: <b>' . mysql_error() .
'</b>');
mysql_select_db('db_students') OR die( 'Could not connect to MySQL because: <b>' . mysql_error() . '</b>');
if (is_numeric($_GET['id'])) {
$query = "DELETE FROM tb_students where id={$_GET['id']}";
if ($r = mysql_query($query))
{
mysql_query('ALTER TABLE tb_students drop id');
print "<center><font size=6><b> Data deleted. </b></font></center>";
}
else
{
print "cannot Delete because: <b> " . mysql_error() . "</b> . The Query was $query . ";
}
}
else {
print "Could not find the Id because: <b>" . mysql_error() . "</b> . The Query was $query . ";
}
mysql_close();
?>
<br><p><br><p><br><p><br><p><br><p><br><p><br><p><br><p><br><p>
<center>
<a href="viewrecords.php" onMouseover="window.status='View Records'; return true" onMouseout="window.status=' ';
return true"> View Records </a>
<br><p>
<a href="inputform.html" onMouseover="window.status='Add New Entry'; return true" onMouseout="window.status=' ';
return true"> Add New Entry </a> </center> </body>
</html>