CS310
CS310
CS310
Complete Handouts
by
Wahab Ahmad & Fatima Ali
2
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 1 Summery
PHP
<? php
echo "Hello World!";
?>
</body>
</html>
5
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 2 Summery
echo "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>";
echo $x + $y;
?>
6
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
The following example shows how to output text with the print command
(notice that the text can contain HTML markup)
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are NOT case-sensitive.
Example
<!DOCTYPE html>
<html>
<body>
<?php
</body>
</html>
7
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
8
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Variable Names
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
9
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Data Types
Variables can store data of different types, and different data types can do
different things.
String
Integer
Float (double)
Boolean
Array
Object
NULL
PHP String
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
11
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
PHP Integer
Example
<?php
$x = 5985;
var_dump($x);
?>
var_dump($x) will return the data type variable.
12
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
In the following example $x is a float.
<?php
$x = 10.365;
var_dump($x);
?>
13
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about
conditional testing in a later chapter of this tutorial.
PHP Object
An object is a data type which stores data and information on how to process
that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A
class is a structure that can contain properties and methods:
Example
<?php
class Car {
function Car() {
14
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
$this->model = “Honda";
}
}
// create an object
$fahad = new Car();
// show object properties
echo $fahad->model;
?>
15
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 3 Summery
PHP is a Loosely Typed Language
PHP automatically converts the variable to the correct data type,
depending on its value.
In other languages, such as C, C++, and Java, the programmer must
declare the name and type of the variable before using it.
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
$x = “Pakistan”
Echo $x
?>
16
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
19
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
myTest();
myTest();
myTest();
?>
20
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
PHP Strings
A string is a sequence of characters, like "Hello world!".
PHP String Functions
Get The Length of a String
The PHP strlen() function returns the length of a string.
The example below returns the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string:
<?php
echo str_word_count("Hello world!");
// outputs 2
?>
21
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Reverse a String
The PHP strrev() function reverses a string:
<?php
echo strrev("Hello world!");
// outputs !dlrow olleH
?>
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match.
If no match is found, it will return FALSE.
Example
The example below searches for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world");
// outputs 6
?>
Replace Text Within a String
The PHP str_replace() function replaces some characters with some other
characters in a string.
The example below replaces the text "world" with "Dolly":
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
Complete PHP String Reference
For a complete reference of all string functions, go to complete PHP
String Reference.
http://www.w3schools.com/php/php_ref_string.asp
The PHP string reference contains description and example of use, for
each function!
22
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire
script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
Example
The example below creates a constant with a case-sensitive name:
23
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
24
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 4 Summery
PHP 5 Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Week 5 Summery
if statement
if statement is used when we want to perform some action if the condition is
true
General PHP syntax
Condition will be
evaluated to true
or false
if(condition)
Code to be executed if condition is true
If there are multiple statements, then statements should be enclosed within curly
braces.
if(condition)
{
Code to be executed if condition is true
}
Examples
<?php
$num1 = 10 ;
$num2 = 5 ;
if ($num1 > $num2)
echo “Number 1 is greater than number 2” ;
?>
Out put of program:
Number 1 is greater than number 2 ;
30
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
$num1 = 5;
$num2 = 10 ;
if ($num1 > $num2)
echo “Number 1 is greater than number 2” ;
?>
Nothing will be displayed on the screen as condition is false
if else statement
This statement is used when we want to perform some action if the condition is
true and another action if condition is not true or false
General PHP syntax
if(condition)
Code to be executed if condition is true
else
Code to be executed if condition is false
Example
<?php
$num1 = 20 ;
$num2 = 10 ;
if ($num1 > $num2)
echo “Number 1 is greater than number 2” ;
else
echo “Number 2 is greater than number 1” ;
?>
31
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
$num1 = 10 ;
$num2 = 20 ;
if ($num1 > $num2)
echo “Number 1 is greater than number 2” ;
else
echo “Number 2 is greater than number 1” ;
?>
Out put of program:
Number 2 is greater than number 1
if elseif else
We use this statement to execute some code if one of the several conditions is
true.
if(condition)
Code to be executed if condition is true
else if(condition)
Code to be executed if condition is true
else if(condition)
Code to be executed if condition is true
32
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
….
else
Code to be executed if condition is false
Example
<?php
$num1 = 10 ;
$num2 = 20 ;
if ($num1 > $num2)
echo “Number 1 is greater than number 2” ;
else if ($num1 < $num2)
echo “Number 1 is less than number 2” ;
else
echo “Both numbers are equal” ;
?>
Out put of program:
Number 1 is less than number 2 ;
<?php
$num1 = 10 ;
$num2 = 10 ;
if ($num1 > $num2)
echo “Number 1 is greater than number 2” ;
else if ($num1 < $num2)
echo “Number 1 is less than number 2” ;
else
33
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Multiple if statements
if(condition)
Code to be executed if condition is true
if(condition)
Code to be executed if condition is true
if(condition)
Code to be executed if condition is true
if(condition)
Code to be executed if condition is true
34
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Switch Statement
We use this statement to select one of several blocks of code to be executed.
….
default:
code to be executed if variable/expression does not match any case
}
Examples
<?php
$signal = 'Y' ;
switch($signal)
{
case 'R':
echo "Red signal" ;
break ;
case 'Y':
echo "Yellow signal" ;
break ;
case 'G':
echo "Green signal" ;
break ;
default:
echo "Invalid signal" ;
}
?>
break statement is used at the end of each case to prevent the code from running
into next case automatically
36
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Output of program
Yellow signal
<?php
$num = 2 ;
switch($num)
{
case '1':
echo "Number 1" ;
break ;
case '2':
echo "Number 2" ;
break ;
case '3':
echo "Number 3" ;
break ;
default:
echo "Not a number from 1 to 3" ;
}
?>
Output of program
Number 2
37
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 6 Summery
for loop
Loops are repetition structures that are used to perform the same task again and
again.
for loops are used to execute same block of code again and again for the
specified number of times.
If we know the exact iteration of loop then for loop must be used.
General PHP syntax
In each iteration, if the condition evaluates to true then loop continues otherwise
if it evaluates to false then loop terminates
38
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
1 0<5 (True) 0 1
2 1<5 (True ) 1 2
3 2<5 (True) 2 3
4 3<5 (True) 3 4
5 4<5 (True) 4 5
<?php
$square = 0 ;
for($i = 0 ; $i<=5; $i++)
{
$square = $i*$i ;
echo “Square of $i is $square <br>” ;
}
?>
Output of program
Square of 0 is 0
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
The following example will output the square of numbers in descending order.
<?php
$square = 0 ;
for($i = 5 ; $i>= 0; $i--)
{
$square = $i*$i ;
echo “Square of $i is $square ” ;
40
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
}
?>
Output of program
Square of 5 is 25
Square of 4 is 16
Square of 3 is 9
Square of 2 is 4
Square of 1 is 1
Square of 0 is 0
while loop
while loops are repetition structures that are used to perform the same task again
and again till the satisfaction of certain condition.
The loop continues to run as long as the condition is true and terminates if the
condition is false.
If we want to repeat the process till the satisfaction of certain condition and the
exact iteration of loop is not known, then while loop must be used.
General PHP syntax:
while(condition)
{
// code to be executed
}
41
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example
$i = 0 ;
while($i<5)
{
echo “value of i is $i <br>” ;
$i++ ;
}
The following example will output the square of numbers as long as the value of
variable i is less than or equal to 5.
<?php
$square = 0 ;
$i = 0 ;
while($i<=5)
{
$square = $i*$i ;
echo “Square of $i is $square <br>” ;
$i++ ;
}
?>
42
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Output of program
Square of 0 is 0
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
do while loop
In do while loop, first the body of loop is executed and then loop is repeated till
the satisfaction of certain condition.
In each iteration of loop, body of loop is executed and then condition is checked
for continuation or termination of loop.
If there is a situation in which a loop must be executed at least once then a do-
while loop must be used.
General PHP syntax:
do
{
// code to be executed
} while(condition) ;
43
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example
$i = 0 ;
do
{
echo “value of i is $i <br>” ;
$i++ ;
} while($i<5) ;
The following example will output the square of numbers as long as the value of
variable i is less than or equal to 5.
<?php
$square = 0 ;
$i = 0;
do
{
$square = $i*$i ;
44
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
For each iteration of loop, the value of current element of array is automatically
assigned to a variable and then array pointer is moved by 1.
foreach(array as value)
{
// code to be executed
}
45
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Examples
The following example will print the values of each element of array using
foreach loop.
<?php
$a = array(1, 2, 3, 4, 5) ;
The following example will calculate the square of each element of array using
foreach loop.
<?php
$a = array(1, 2, 3, 4, 5) ;
Week 7 Summery
PHP Include Statement
The include statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP,
HTML, or text on multiple pages of a website.
Syntax
include 'filename';
PHP include Example
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright; 1990-" . date("Y") . " ABC.com</p>";
?>
To include the footer file in a page, use the include statement:
<html>
<body>
</body>
</html>
47
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Note that the PHP date() function will return the current date/time of the
server!
Get a Simple Date
The required format parameter of the date() function specifies how to
format the date (or time).
Here are some characters that are commonly used for dates:
◦ d - Represents the day of the month (01 to 31)
◦ m - Represents a month (01 to 12)
◦ Y - Represents a year (in four digits)
◦ l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the
characters to add additional formatting.
Example
The example below formats today's date in three different ways:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
48
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
So, if you need the time to be correct according to a specific location, you
can set a timezone to use.
49
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
The example below sets the timezone to "Asia/Karachi", then outputs the
current time in the specified format:
Example
<?php
date_default_timezone_set("Asia/Karachi");
echo "The time is " . date("h:i:sa");
?>
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send
the cookie too.
With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
Note: The setcookie() function must appear BEFORE the <html> tag.
Example
<?php
$cookie_name = "user";
$cookie_value = "Ahmed";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 =
1 day
?>
50
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];}
?>
</body></html>
The value of the cookie is automatically URL encoded when sending the
cookie, and automatically decoded when received (to prevent URL encoding,
use setrawcookie() instead).
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Akmal Khan";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
51
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600,"/");
?>
<html><body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body></html>
52
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body></html>
53
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 8 Summery
PHP Sessions
What is a Session?
A session is a way to store information (in variables) to be used across
several pages.
Unlike a cookie, the information is not stored on the user’s computer.
When you work with an application, you open it, do some changes, and
then you close it. This is much like a Session.
On the internet, there is one problem: the web server does not know who
you are, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be
used across multiple pages (e.g. username etc.). By default, session
variables last until the user closes the browser.
Session variables hold information about one single user, and are
available to all pages in one application.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "session_demo1.php". In this page,
we start a new PHP session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html><body>
54
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body></html>
Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.
Get PHP Session Variable Values
Next, we create another page called "session_demo2.php". From this
page, we will access the session information we set on the first page
("session_demo1.php").
Session variables are not passed individually to each new page, instead
they are retrieved from the session we open at the beginning of each page
(session_start()).
All session variable values are stored in the global $_SESSION variable
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
55
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
How does it work?
Most sessions set a user-key on the user's computer that looks something
like this: 765487cf34ert8dede5a562e4f3a7e12.
Then, when a session is opened on another page, it scans the computer for
a user-key.
If there is a match, it accesses that session, if not, it starts a new session.
56
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body></html>
57
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 9 Summery
PHP Filters
Why Use Filters?
Filters are used for
Validating data = Determine if the data is in proper form.
Sanitizing data = Remove any illegal character from the data.
Many web applications receive external input. External input/data can be:
◦ User input from a form
◦ Cookies
◦ Web services data
◦ Server variables
◦ Database query results
You should always validate external data!
Invalid submitted data can lead to security problems and break your
webpage!
By using PHP filters you can be sure your application gets the correct
input!
PHP filter_var() Function
The filter_var() function both validate and sanitize data.
Sanitize a String
The following example uses the filter_var() function to remove all HTML
tags from a string:
Example
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
Sanitize and Validate a URL
The following example uses the filter_var() function to first remove all
illegal characters from a URL, then check if $url is a valid URL:
Example
<?php
$url = "http://www.vu.edu.pk";
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
59
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
$email = "john.doe@example.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Validate an Integer
The following example uses the filter_var() function to check if the
variable $int is an integer. If $int is an integer, the output of the code
above will be: "Integer is valid". If $int is not an integer, the output will
be: "Integer is not valid":
Example
<?php
$int = 100;
if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
60
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
} else {
echo("Integer is not valid");
}
?>
Tip: filter_var() and Problem With 0
In the previous example, if $int was set to 0, the function above will
return "Integer is not valid". To solve this problem, use the code below:
Example
<?php
$int = 0;
if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int,
FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Validate an IP Address
The following example uses the filter_var() function to check if the
variable $ip is a valid IP address:
Example
<?php
$ip = "127.0.0.1";
if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
echo("$ip is a valid IP address");
61
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
} else {
echo("$ip is not a valid IP address");
}
?>
Week 10 Summery
Introduction to MySQL Database
Data base
◦ A database is an organized collection of data.
Database management system (DBMS)
◦ It is a computer software application, designed to allow the
definition, creation, querying, update, and administration of
databases.
◦ Example
Some examples of DBMS are :
MySQL
PostgreSQL
Microsoft SQL Server
Oracle
Sybase
MySQL Database
A free, fast, reliable, easy-to-use, multi-user multi-threaded relational
database system.
SQL (Structured Query Language) is use in MYSQL database system.
It is freely available and released under GPL (GNU General Public
License ).
Officially pronounced “my Ess Que Ell” (not my sequel).
62
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
MySQL Connect
Earlier versions of PHP used the MySQL extension. PHP version 5 and
after that work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
PDO will work on 12 different database systems, where as MySQLi will
only work with MySQL databases.
Three ways of working with PHP and MySQL:
i- MySQLi (object-oriented)
ii- MySQLi (procedural)
iii- PDO
MySQL Create DB
The CREATE DATABASE statement is used to create a database in MySQL.
Examples
<?PHP $servername = "localhost";
$username = “root";
64
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
$password = “";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}
// Create database
$sql = "CREATE DATABASE mystudent";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
} ?>
65
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 11 Summery
MySQL Create Table
The CREATE TABLE statement is used to create a table in MySQL.
We will create a table named “Student", with five columns: “s_id",
"firstname", "lastname", "email" and "reg_date":
SQL Statement:
CREATE TABLE Student (
s_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
Example:
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
66
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table student created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL Insert Data
When a database and a table have been created, we can start adding data
in them.
Here are some syntax rules to follow:
The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL
table
The INSERT INTO statement is used to add new records to a MySQL
table:
SQL Statement: INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Note: If a column is AUTO_INCREMENT (like the "id" column) or
TIMESTAMP (like the "reg_date" column), it is no need to be specified in the
SQL query; MySQL will automatically add the value.
67
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO student (firstname, lastname, email)
VALUES (‘Ali', ‘Wali', ‘ali@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL Get Last ID
we perform an INSERT or UPDATE on a table with an
AUTO_INCREMENT field, we can get the ID of the last
inserted/updated record immediately.
In the table “student", the "id" column is an AUTO_INCREMENT field:
68
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL Insert in Multiple.
Multiple SQL statements must be executed with the
mysqli_multi_query() function.
The following examples add three new records to the “student" table:
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
69
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
mysqli_close($conn);
?>
MySQL Prepared.
A prepared statement is a feature used to execute the same (or similar)
SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the database.
Certain values are left unspecified, called parameters (labeled "?").
Example: INSERT INTO student VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on the
SQL statement template, and stores the result without executing it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement.
The application may execute the statement as many times as it wants with
different values
70
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO student (firstname, lastname,
email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$firstname = “Amna";
$lastname = “khan";
$email = “amna@example.com";
$stmt->execute();
$firstname = “Zanub";
$lastname = “ali";
$email = “zanub@example.com";
$stmt->execute();
$stmt->close();
$conn->close();
?>
72
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 12 Summery
MySQL Select Data
The SELECT statement is used to select data from one or more tables:
Example
SELECT column_name(s) FROM table_name
we can use the * character to select ALL columns from a table:
Example
SELECT * FROM table_name
Example
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM student";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
73
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
mysqli_close($conn);
?>
MySQL Delete Data
The DELETE statement is used to delete records from a table.
SQL Statement:-DELETE FROM table_name
WHERE some_column = some_value.
Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
74
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
75
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 13 Summery
PHP File Handling
File handling is an important part of any web application. You often need
to open and process a file for different tasks.
PHP has several functions for creating, reading, uploading, and editing
files.
Be careful when manipulating files!
When you are manipulating files you must be very careful. You can do a
lot of damage if you do something wrong.
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
80
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next
line.
81
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
82
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 14 Summery
PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a little confusing,
but in PHP, a file is created using the same function used to open files.
If you use fopen() on a file that does not exist, it will create it, given that
the file is opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be
created in the same directory where the PHP code resides:
Example
Example explained
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote
to the file we sent the string $txt that first contained "John Doe" and
second contained "Jane Doe". After we finished writing, we closed the
file using the fclose() function.
</body>
</html>
Some rules to follow for the HTML form are:
Make sure that the form uses method="post"
The form also needs the following attribute: enctype="multipart/form-
data". It specifies which content-type to use when submitting the form
Without the requirements above, the file upload will not work.
}?>
First, we will check if the file already exists in the "uploads" folder. If it
does, an error message is displayed, and $uploadOk is set to 0:
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
The code above will get an error like this:
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6
Try, throw and catch
To avoid the error from the example above, we need to create the proper
code to handle an exception.
Proper exception code should include:
1. Try - A function using an exception should be in a "try" block. If
the exception does not trigger, the code will continue as normal.
However if the exception triggers, an exception is "thrown"
2. Throw - This is how you trigger an exception. Each "throw" must
have at least one "catch"
3. Catch - A "catch" block retrieves an exception and creates an
object containing the exception information
91
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
The code above will get an error like this:
Example explained:
The code throws an exception and catches it:
1. The checkNum() function is created. It checks if a number is
greater than 1. If it is, an exception is thrown
2. The checkNum() function is called in a "try" block
3. The exception within the checkNum() function is thrown
4. The "catch" block retrieves the exception and creates an object ($e)
containing the exception information
5. The error message from the exception is echoed by calling $e-
>getMessage() from the exception object
Creating a Custom Exception Class
Creating a custom exception handler is quite simple.
We simply create a special class with functions that can be called when
an exception occurs in PHP.
The class must be an extension of the exception class.
The custom exception class inherits the properties from PHP's exception
class and you can add custom functions to it.
Example
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "someone@example...com";
try {
93
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>
The new class is a copy of the old exception class with an addition of the
errorMessage() function.
Since it is a copy of the old class, and it inherits the properties and methods
from the old class, we can use the exception class methods like getLine() and
getFile() and getMessage().
Example explained:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "someone@example...com";
try {
//check if
94
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example explained:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "someone@example...com";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
95
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>
The errorMessage() function is created. This function returns an error message
if an e-mail address is invalid
Example explained:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "someone@example...com";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
96
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example explained:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "someone@example...com";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>
The "try" block is executed and an exception is thrown since the e-mail address
is invalid
97
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Example explained:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "someone@example...com";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>
The "catch" block catches the exception and displays the error message
98
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 15 Summery
WordPress
What is WordPress
WordPress is web software you can use to create a beautiful website, blog, or
app. We like to say that WordPress is both free and priceless at the same time.
WordPress Examples
https://wordpress.org/showcase/
99
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Benefits of WordPress
Free
Easy to use
Written in PHP
MySQL Database at back end
Easy customization (Themes)
Simple to understand
Things to Know Before Installing WordPress
Access to your web server
A text editor
An FTP Client
Your web browser of choice
Requirements
You must be able to execute PHP at your web server
Access to an MySql Database
In simple you web hosting company should provide PHP and MySQL
support
Installing WORDPRESS on Localhost
Access to your web server www directory
A text editor
Your web browser of choice
MySQL Database
Installing on Remote Host
Access to your web server www or public_html directory
A text editor
An FTP Client
100
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Week 16 Summery
Adding Pages to your Website
Find the Pages menu in the WordPress Dashboard Navigation menu.
Click Add new.
Add the title of the page, like About. Note: If you have pretty
permalinks set up, the title of your page will also be the URL slug.
Next, add some content.
To Publish the page click on save and publish
Website Homepage
Go to Pages → Add.
Call it “Home.” Don’t worry about writing any thing it yet.
To designate your static homepage, go to Appearance → Customize →
Static Front Page:
Then, under Front page displays, choose Static page. Next, click on
the Front page dropdown list and select the “Home” page you created as
your static homepage:
101
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
Click the Add to Menu button located at the bottom of this pane to add
your selection(s) to the menu that you created in the previous step.
Click the Save Menu button once you've added all the menu items you
want.
Deleting a Menu Item
Locate the menu item that you want to remove in the menu editor
window
Click on the arrow icon in the top right-hand corner of the menu item/box
to expand it.
Click on the Remove link. The menu item/box will be immediately
removed.
Click the Save Menu button to save your changes.
Complete GUIDE
https://codex.wordpress.org/WordPress_Menu_User_Guide
WordPress Themes
WordPress themes are simply a group of files, called templates, which
determine the look and basic function of your site
Free vs paid themes
See Audio Lectures
Free themes
https://wordpress.org/themes/
Paid themes
http://www.templatemonster.com/wordpress-themes.php
http://themeforest.net/
http://www.themezilla.com/themes/
103
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
WordPress Plugins
Plugins tiny pieces of software which are used to extend and add to the
functionality that already exists in WordPress.
The core of WordPress is designed to be lean and lightweight, to maximize
flexibility and minimize code bloat. Plugins then offer custom functions and
features so that each user can tailor their site to their specific needs.
https://wordpress.org/plugins/
Example
We need to have employee list for our website which we have developed in
WordPress.
We can use plugins like
Employee Spotlight
Simple Staff List
OS Our Team
WordPress Theme Customization
Theme Customizer
The Theme Customizer allows you to preview changes to your site before
publishing them. You can also navigate to different pages on your site to
preview them.
Site Title & Tagline
Colors
Header Image
Background Image
Navigation
Widgets
Static Front Page
Further reading
https://codex.wordpress.org/Appearance_Customize_Screen
104
CS310 - Open Source Web Application Development (PHP, PERL,
CGI, Mysql)
THE END