You are on page 1of 45

Database

Systems

PHP

PHP and Database Systems


PostgreSQL
PHP & SQL

Departamento de Engenharia Informática


Instituto Superior Técnico

1st Semester
2010/2011
Outline

Database
Systems

PHP
1 PHP
PHP and
The PHP Language
PostgreSQL
Language Constructs
Arrays
Conditional Statements
Loops
Changing Pages

2 PHP and PostgreSQL


Interacting with the Database
Using HTML Forms
Outline

Database
Systems

PHP
The PHP
1 PHP
Language
Language
The PHP Language
Constructs
Arrays Language Constructs
Conditional
Statements
Loops
Arrays
Changing Pages Conditional Statements
PHP and
PostgreSQL
Loops
Changing Pages

2 PHP and PostgreSQL


PHP

Database
Systems

PHP
The PHP PHP: PHP Hypertext Preprocessor
Language
Language
Constructs Server-side scripting language
Arrays
Conditional
Statements
Designed for the dynamic generation of Web pages
Loops
Changing Pages Runs on many platforms (Linux, Mac, Windows, ...)
PHP and
PostgreSQL Integrated with many Web servers (Apache, IIS, ...)
Supports many databases (PostgreSQL, Oracle, ...)
Well integrated with PostgreSQL
It’s Open Source and Free Software (FSF-approved)
How PHP Works

Database
Systems

PHP
The PHP
Language
Installed with a Web server and a DMBS
Language
Constructs Usually Apache and MySQL/PostgreSQL
Arrays
Conditional
Statements
When the browser is pointed to a PHP file (.php)
Loops
Changing Pages
1 The server processes the file and sends any HTML
PHP and statements
PostgreSQL 2 When the server reaches a PHP tag (<?php) it executes
the PHP statements and sends the resulting output
3 When an ending tag is reached (?>), the server switches
back to sending HTML statements
A simple program

Database
Systems

PHP
The PHP
<html>
Language
Language <head>
Constructs
Arrays <title>PHP Test</title>
Conditional
Statements
Loops
</head>
Changing Pages
<body>
PHP and
PostgreSQL <?php echo ’<p>Hello World</p>’; ?>
</body>
</html>
(test me here)
Variables

Database
Systems
No need to declare variables, just assign a value
PHP $age = 12;
The PHP
Language
Language
$price = 2.55;
Constructs
Arrays $number=-2;
Conditional
Statements $name = "Goliath Smith";
Loops
Changing Pages

PHP and
Variable names:
PostgreSQL start with $
can include only letters, numbers and underscore
cannot begin with a number
Clearing variables

unset($age);

Note: PHP is case-sensitive


Constants

Database
Systems

PHP
The PHP
Language
Language
Constructs
Constants are set using the define statement
Arrays
Conditional
Statements define("COMPANY","ABC Pet Store");
Loops
Changing Pages define("AGE",29);
PHP and
PostgreSQL
echo COMPANY;
echo AGE;
Operators

Database
Systems
PHP can perform arithmentic operations
+, −, ∗, /, %
PHP
The PHP
Language
Example:
Language
Constructs
Arrays
Conditional
$result = (1 + 2) * 4 + 1;
Statements
Loops
Changing Pages The following comparison operators are available:
PHP and ==, >, <, >=, <=, ! = (or <>)
PostgreSQL
Example:

$weather == "raining"
$age < 13

Plus the logical operators


and (or &&), or (or ||), xor and !
Strings

Database
Systems A string:
$string = ’Hello World!’;
PHP
The PHP
Language
Language
Quote characters (” and ’) must be escaped
Constructs
Arrays
Conditional
Statements
$string = ’It is Tom\’s house’;
Loops
Changing Pages
String concatenation:
PHP and
PostgreSQL
$string1 = ’Hello’;
$string2 = ’World!’;
$stringall = $string1 . ’ ’ . $string2;

Formatting strings:
$price = 25;
$fprice = sprintf("%01.2f", $price);
Single-Quotes versus Double-Quotes

Database
Systems Single-quoted strings (using ’) are represented as is
$age = 12;
PHP
The PHP
echo ’The age is $age’;
Language
Language
Constructs
Arrays
yields
Conditional
Statements
Loops The age is $age
Changing Pages

PHP and Double-quoted strings (using ”) are processed


PostgreSQL

$age = 12;
echo "The age is $age";

yields
The age is 12

Special characters are also recognized


\n, \t, ...
Dates and Times

Database
Systems Getting the current date and time
$today = time();
PHP
The PHP
Language
Language
Formatting a date
Constructs
Arrays
Conditional
Statements
$cdate = date("d/m/y", $today);
Loops
Changing Pages
$ctime = date("G:i:s", $today);
PHP and
PostgreSQL Many formatting options:
M: month abbreviated
F: month not abbreviated
...
Converting strings to dates
$importantDate = strtotime("January 15 2003");
(test me here)
Date Operations

Database
Systems
PHP can perform date arithmetic
PHP
The PHP $timeSpan = $today - $importantDate;
Language
Language
Constructs
Arrays returns the number of seconds between both dates
Conditional
Statements
Loops
Conversion from strings also accepts many operations
Changing Pages

PHP and
PostgreSQL
$importantDate = strtotime("tomorrow");
$importantDate = strtotime("now + 24 hours");
$importantDate = strtotime("last saturday");
$importantDate = strtotime("8pm + 3 days");
$importantDate = strtotime("2 weeks ago");
$importantDate = strtotime("next year gmt");
$importantDate = strtotime("this 4am");
Regular Expressions

Database
Systems

PHP supports regular expressions


PHP
The PHP
Language ereg("pattern", string);
Language
Constructs
Arrays
Conditional returns true if pattern matches string
Statements
Loops
Changing Pages
Example:
PHP and
PostgreSQL ereg("^[A-Za-z’ -]+$", $name)

checks the validity of a name


Replacements:

$new = ereg_replace($expression,$replacement,$old)
Other Useful Statements

Database
Systems
PHP contains self-referring arithmetic operators operators
PHP
The PHP
$counter += 2;
Language
Language $counter -= 3;
Constructs
Arrays $counter *= 2;
Conditional
Statements
Loops
$counter /= 3;
Changing Pages

PHP and Exiting a PHP program


PostgreSQL

exit("The program is exiting");

or
die("The program is dying");

Comments can be inserted using /* ... */ or #


Functions

Database
Systems

PHP
The PHP
Language
Language
Constructs
Arrays function add_2_numbers($num1 = 1, $num2 = 1)
Conditional
Statements
Loops
{
Changing Pages $total = $num1 + $num2;
PHP and
PostgreSQL return $total;
}
Creating Arrays

Database
Systems Simple array
$pets[1] = "cat";
PHP
The PHP
$pets[2] = "dog";
Language
Language
$pets[3] = "monkey";
Constructs
Arrays
Conditional
Statements
or
Loops
Changing Pages $pets = array("cat","dog","monkey");
PHP and
PostgreSQL
Key-indexed array
$capitals[’PT’] = "Lisbon";
$capitals[’AU’] = "Canberra";
$capitals[’BR’] = "Brasilia";

or
$capitals = array("PT" => "Lisbon",
"AU" => "Canberra", "BR" => "Brasilia");
Sorting Arrays

Database
Systems

PHP Sorting simple arrays


The PHP
Language
Language
Constructs sort($pets);
Arrays
Conditional
Statements
Loops
Sorting key-indexed arrays
Changing Pages

PHP and asort($capitals);


PostgreSQL

Other sort methods:


rsort, arsort: reversed sort
ksort, krsort: sort by key
usort($array,function): sort using function
Moving Through an Array

Database
Systems
Arrays can behave as iterators
PHP
The PHP
reset($capitals);
Language
Language
Constructs
Arrays $value = current($capitals);
Conditional
Statements echo "$value<br>";
Loops
Changing Pages

PHP and
PostgreSQL
$value = next($capitals);
echo "$value<br>";

$value = next($capitals);
echo "$value<br>";
Other statements:
previous, end, sizeof
Moving Through an Array (cont.)

Database
Systems

PHP Can use the foreach statement


The PHP
Language
Language
Constructs
$capitals = array ( "PT" => "Lisbon",
Arrays
Conditional
"AU" => "Canberra", "BR" => "Brasilia" );
Statements
Loops ksort ($capitals);
Changing Pages
foreach ( $capitals as $state => $city )
PHP and
PostgreSQL {
echo "$city, $state<br>";
}

(test me here)
Multidimensional Arrays

Database
Systems

PHP
Creating a multidimensional array
The PHP
Language
Language $productPrices[’clothing’][’shirt’] = 20.00;
Constructs
Arrays $productPrices[’clothing’][’pants’] = 22.50;
Conditional
Statements
Loops
$productPrices[’linens’][’blanket’] = 25.00;
Changing Pages
$productPrices[’linens’][’bedspread’] = 50.00;
PHP and
PostgreSQL $productPrices[’furniture’][’lamp’] = 44.00;
$productPrices[’furniture’][’rug’] = 75.00;

Using multidimensional arrays

$shirtPrice = $productPrices[’clothing’][’shirt’];
Multidimensional Arrays (cont.)

Database
Systems <?php
$productPrices[’clothing’][’shirt’] = 20.00;
$productPrices[’clothing’][’pants’] = 22.50;
PHP
The PHP $productPrices[’linens’][’blanket’] = 25.00;
Language
Language
$productPrices[’linens’][’bedspread’] = 50.00;
Constructs
Arrays
$productPrices[’furniture’][’lamp’] = 44.00;
Conditional
Statements
$productPrices[’furniture’][’rug’] = 75.00;
Loops
Changing Pages
echo "<table border=1>";
PHP and
PostgreSQL foreach( $productPrices as $category ) {
foreach( $category as $product => $price ) {
$f_price = sprintf("%01.2f", $price);
echo "<tr><td>$product:</td><td>\$$f_price</td></tr>";
}
}
echo "</table>";
?>

(test me here)
The if Statement

Database
Systems

if ($country == "Germany" )
PHP
{
The PHP $version = "German";
Language
Language $message = " Sie sehen unseren Katalog auf Deutsch";
Constructs
Arrays }
Conditional
Statements elseif ($country == "France" )
Loops {
Changing Pages
$version = "French";
PHP and
PostgreSQL $message = " Vous verrez notre catalogue en francais";
}
else
{
$version = "English";
$message = "You will see our catalog in English";
}
echo "$message<br>";
The switch Statement

Database
Systems

PHP switch ($custCountry)


The PHP {
Language
Language
Constructs
case "PT" :
Arrays $salestaxrate = 0;
Conditional
Statements break;
Loops
Changing Pages case "AU" :
PHP and $salestaxrate = 1.0;
PostgreSQL break;
default:
$salestaxrate = .5;
break;
}
$salestax = $orderTotalCost * $salestaxrate;
The for Loop

Database
Systems

PHP
The PHP
for ($i = 0; $i < sizeof($customerNames); $i++)
Language
Language
{
Constructs
Arrays echo "$customerNames[$i]<br>";
Conditional
Statements }
Loops
Changing Pages

PHP and
PostgreSQL for ($i = 0, $j = 1;$t <= 4; $i++, $j++)
{
$t = $i + $j;
echo "$t<br>";
}
The while Loop

Database
Systems

while ($testvar != "yes")


PHP {
The PHP
Language
Language
if ($customers[$k] == "Smith")
Constructs
Arrays
{
Conditional
Statements $testvar = "yes";
Loops
Changing Pages echo "Smith<br>";
PHP and
PostgreSQL
}
else
{
echo "$customers[$k], not Smith<br>";
}
$k++;
}
The do...while Loop

Database
Systems
do
{
PHP
The PHP
if ($customers[$k] == "Smith")
Language
Language {
Constructs
Arrays $testvar = "yes";
Conditional
Statements
Loops
echo "Smith<br>";
Changing Pages
}
PHP and
PostgreSQL else
{
echo "$customers[$k], not Smith<br>";
}
$k++;
} while ($testvar != "yes")

Note: continue and break statements can be used


Redirecting the Browser

Database
Systems

The PHP header function can be used to send a new page


PHP
The PHP to the browser
Language
Language
Constructs
Arrays
if ($customer_age < 13)
Conditional
Statements {
Loops
Changing Pages header("Location: ToyCatalog.php");
PHP and }
PostgreSQL
else
{
header("Location: ElectronicsCatalog.php");
}
Note: the header function must appear before any output is sent
Using Cookies

Database
Systems

Setting cookies
PHP
The PHP
Language
Language
setcookie("country","PT");
Constructs
Arrays
Conditional
Statements
or
Loops
Changing Pages
setcookie("country","PT",time()+3600);
PHP and
PostgreSQL
All values stored as cookies are available in the $_COOKIE
array

echo $_COOKIE[’country’];

Note: the setcookie function must be used before any output is sent
PHP Sessions

Database
Systems

PHP Cookies are not always available


The PHP
Language
Language
PHP provides a safer mechanism: sessions
Constructs
Arrays When a session is started, PHP
Conditional
Statements
Loops
If the session exists, uses it, if not creates a new session
Changing Pages number
PHP and
PostgreSQL
Stores session variables in a file, on the server
Passes the session id number to every page
through cookies, the URL, or a hidden post variable
For each new page, gets the variables from thew session
file
The variables are accessible in the $ SESSION array
Using a Session

Database
Systems
To start a session
PHP
The PHP
session_start()
Language
Language
Constructs Note: session start must be used before any output is sent
Arrays
Conditional
Statements
Using session variables
Loops
Changing Pages
$_SESSION[’country’] = "PT";
PHP and
PostgreSQL
and, on a different page

echo $_SESSION[’country’];

Closing the session

session_destroy();
Session Example

Database
Systems

<?php
PHP
session_start();
The PHP ?>
Language
Language <html>
Constructs
Arrays <head><title>Testing Sessions page 1</title></head>
Conditional <body>
Statements
Loops <?php
Changing Pages
$_SESSION[’session_var’] = "testing";
PHP and
PostgreSQL echo "This is a test of the sessions feature.
<form action=’sessionTest2.php’ method=’POST’>
<input type=’hidden’ name=’form_var’
value=’testing’>
<input type=’submit’ value=’go to next page’>
</form>";
?>
</body></html>
Session Example (cont.)

Database
Systems

PHP
<?php
The PHP session_start();
Language
Language ?>
Constructs
Arrays
<html>
Conditional
Statements
<head><title>Testing Sessions page 2</title></head>
Loops <body>
Changing Pages
<?php
PHP and
PostgreSQL echo "session_var = {$_SESSION[’session_var’]}<br>\n";
echo "form_var = {$_POST[’form_var’]}<br>\n";
?>
</body></html>

(test me here)
Outline

Database
Systems

PHP

PHP and
PostgreSQL 1 PHP
Interacting with
the Database
Using HTML
Forms
2 PHP and PostgreSQL
Interacting with the Database
Using HTML Forms
Connecting to the Database

Database
Systems

Inline error handling


PHP

PHP and
$conn_str = "host=$host port=$port user=$user
PostgreSQL password=$password";
Interacting with
the Database $connection = pg_connect($conn_str)
Using HTML
Forms or die("Couldn’t connect to server");

Testing for errors

if (!$connection = pg_connect($conn_str))
{
$message = pg_last_error();
echo "$message<br>";
die();
}
Connecting to the Database (cont.)

Database
Systems

PHP
Selecting the database
PHP and
PostgreSQL
Interacting with
the Database
$dbname = "bank";
Using HTML
Forms $conn_str = "host=$host port=$port user=$user
password=$password dbname=$dbname";
$connection = pg_connect($conn_str);

Closing the connection

pg_close($connection);
Sending Queries

Database
Systems

PHP
$result = pg_query($query)
PHP and
or die("Couldn’t execute query.");
PostgreSQL
Interacting with
the Database or
Using HTML
Forms
$result = pg_query($connection,$query)
or die("Couldn’t execute query.");

For queries that return data, $result is a pointer to the


results
For queries that do not return data, $result contains
true is the statement succeeded, false if otherwise
Fetching the Results

Database
Systems

PHP

PHP and
Results are fetched into an array
PostgreSQL
Interacting with
the Database $row = pg_fetch_assoc($result);
Using HTML
Forms while($row)
{
$valor = $row["atributo"];
echo "<p>$valor</p>";
$row = pg_fetch_assoc($result);
}
Example

Database
Systems <table border=1>
<tr><td><b>Name</b></td><td><b>Street</b></td>
<td><b>City</b></td></tr>
PHP
<?php
PHP and
PostgreSQL
$sql="select * from customer";
Interacting with $result = pg_query($sql);
the Database
Using HTML echo "N. of results: " . pg_num_rows($result)";
Forms
echo "N. of columns: " . pg_num_fields($result)";
while($row_array = pg_fetch_assoc($result))
{
echo "<tr>";
echo "<td>{$row_array[’customer_name’]}</td>";
echo "<td>{$row_array[’customer_street’]}</td>";
echo "<td>{$row_array[’customer_city’]}</td>";
echo "</tr>";
}
?>
</table>

(test me here)
Processing Forms

Database
Systems An HTML form
<form action="processform.php" method="post">
PHP

PHP and
<p>Your name: <input type="text" name="name" /></p>
PostgreSQL <p>Your age: <input type="text" name="age" /></p>
Interacting with
the Database
Using HTML
<p><input type="submit" /></p>
Forms
</form>
Program processform.php will have access to the forms
fields through the arrays
$_POST: contains elements for all the fields contained in a
form if the form uses method POST
$_GET: contains elements for all the fields contained in a
form if the form uses method GET
$_REQUEST: contains all elements in $_POST, $_GET and
$_COOKIE
Example: $_POST[’name’]
Processing Forms Example

Database
Systems
<?php
PHP

PHP and
echo "<html>
PostgreSQL <head><title>Customer Address</title></head>
Interacting with
the Database
Using HTML
<body>";
Forms

foreach ($_POST as $field => $value)


{
echo "$field = $value<br>";
}
?>
</body></html>

(test me here)
Using Checkboxes

Database
Systems

Checkboxes allow multiple choice values


PHP

PHP and <input type=’checkbox’ name=’type[account]’


PostgreSQL
Interacting with
the Database
value=’account’>
Using HTML
Forms
<input type=’checkbox’ name=’type[loan]’
value=’loan’>
In this case, the variable $_POST[’type’] is also an array,
such that
$_POST[’type’][’account’] == ’account’
$_POST[’type’][’loan’] == ’loan’

if both ”account”and ”loan”where selected.


Cleaning the Input Data

Database
Systems

PHP

PHP and PHP provides some useful functions to clean the user input
PostgreSQL
Interacting with strip tags: removes all HTML tags
the Database
Using HTML
Forms htmlspecialchars: converts all special characters to safe
HTML entities
Example:

$last_name = strip_tags($last_name,"<b><i>");
$last_name = htmlspecialchars($last_name);
References

Database
Systems

PHP

PHP and
PostgreSQL
Interacting with
the Database
Using HTML
The W3Schools PHP Tutorial
Forms
http://www.w3schools.com/php/default.asp
The PHP Web site
http://www.php.net/
Database
Systems

PHP

PHP and
PostgreSQL
Interacting with
the Database
Using HTML
Forms

The End