Вы находитесь на странице: 1из 65

PHP & MySQL by

Examples
Simone Grassi
PhD at Trinity College Dublin
Research on Software Architectures
Distributed Systems Group
grassis@cs.tcd.ie
PHP Advantages

Multiplatform
Supports most important Databases
Wide set of included functions
Many Open Source resources (es: PEAR http://
pear.php.net)
Included in many Linux distributions
40% of Internet Domains uses PHP
Wide International Community (in 2 clicks from
google you find the solution for 99% of problems)
PHP is a scripting language
PHP has an HTML-centric approach making easy and fast to
develop scripts for the web.
<!-- example_1.php -->
<html><header><title>PHP Example</title></header>
<body><h1>My Example</h1>
<form action="example_1.php" method="POST">
FirstName: <input type="text" name="firstname"><br/>
LastName: <input type="text" name="lastname"><br/>
Born (yyyy - mm - dd) :
<input type="text" name="year" size="4"> -
<input type="text" name="month" size="2"> -
<input type="text" name="day" size="2"><br/>
</form>
<?php
if ($_POST['firstname']) {
$weekday = date('l',mktime(0,0,0,$month,$day,$year));
print "Hi $firstname $lastname, you were born on $weekday";
}
?>
</body></html>
PHP is Server Side (I)
The client doesn't care about PHP, just receive an HTML/JS
(or XHTML/CSS/JS) page.
The web server work in touch with PHP (usually like
a module) and let PHP do the interpretation of the Client Browser
script.
The result of the interpretation is sent back to the 1) Request
browser. 5) Reply (hello_world.php)
BENEFITS
- Concentrate complexity in the server
- Configure only the server to communicate with a third Apache
party database (like MySQL)
PHP
DRAWBACKS
- The server must execute all requests 2) Read
- Saving the output pages from the client does not allow to 4) Collect
create a real copy of the web site output <!-- hello_world.php -->
<html>
<!-- hello_world.php --> <head>
<html> <title>Test Page</title>
<head> 3) Interpretation </head>
<title>Test Page</title> <?
</head> echo ‘Hello World!’;
Hello World! ?>
</body> </body>
</html> </html>
PHP is Server Side (II)
- Only the PHP output
becomes a browser page Client Browser
- Everything outside <? ?>
tags is simply “forwarded” to 5) Reply
1) Request
the output (helloWorld.php)

Apache
PHP
2) Read
4) Collect <!-- no_output.php -->
output <html>
<head>
<!-- no_output.php --> <title>Test Page</title>
<html> 3) Interpretation </head>
<head> <?
<title>Test Page</title> if ($a == 10)
</head> $b = $a;
</body> else
</html> $b = $a * 10;
?>
</body>
</html>
Learning PHP
✔ Basic syntax (similar to c, perl)
✔ Types and Variables
✔ Array, Hash
✔ String manipulation
✔ File management
✔ Expressions, Operators
✔ Control Structure
✔ Functions
✔ Function Reference
✔ Classes and Objects

http://www.php.net/manual/en/
PHP Variables (I)
- The char $ (dollar) is used to specify a variable like: $my_variable,
$_anther_variable.
- No number as first char, $1_name is not allowed.

PHP is loosly typed, the interpreter make on the flight decision about
variable type. If you add two values, PHP tries to cast them to int and then
do the add operation:

<? // variables_1.php
$add = '1' + 1;
echo $add.'<br/>'; // outputs ‘2’
$add = 1 + 'test';
echo $add.'<br/>'; // outputs ‘1’
$add = 'long'+' '+'composed string';
echo $add.'<br/>'; // outputs ‘’
$add = 'long'.' '.'composed string';
echo $add.'<br/>'; // outputs ‘long composed string’
echo '$add'.'<br/>'; // outputs ‘$add’
echo "this is my string: $add"; // outputs ‘this is my string: long composed string’
?>
PHP Variables (II)
Function isset tests if a variable is assigned or not:
$A = 1;
if (isset($A))
print “A isset”;
if (!isset($B))
Using $$:
print “B is NOT set”;
$help = “hiddenVar”;
$$help = “hidden Value”;
echo $$help; // prints hidden Value
$$help = 10;
Is like: $help = $$help * $$help;
$hiddenVar = “hidden Value”; echo $help; // print 100
A string is a sequence of chars:
$stringTest = "this is a sequence of chars";
Strings (I)
for ($i=0;$i<strlen($stringTest);$i++) {
$char_i = $stringTest[$i];
print $char_i;
}
echo $stringTest;
A single quoted strings is displayed “as-is”:
$age = 37;
$stringTest = 'I am $age years old'; // output: I am $age years
old
$stringTest = “I am $age years old”; // output: I am 37 years
old
Concatenation:

$conc = ”is “.”a “.”composed “.”string”;


echo $conc; // output: is a composed string
$newConc = 'Also $conc '.$conc;
echo $newConc; // output: Also $conc is a composed string
Strings (II)
Explode function:

$sequence = “A,B,C,D,E,F,G”;
$elements = explode (“,”,$sequence);
// Now elements is an array with all substrings between “,” char
print_r($elements);

var_dump($elements);

The output is:


Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G )
Arrays (I)
Groups a set of variables, every element stored into an array as an
associated key (index to retrieve the element)

$books = array( 0=>”php manual”,1=>”perl manual”,2=>”C


manual”);
$books = array( 0=>”php manual”,”perl manual”,”C
manual”);
$books = array (“php manual”,”perl manual”,”C manual”);
echo $books[2]; // output: C manual
Arrays with PHP are associative
$books = array( “php manual”=>1,”perl manual”=>1,”C
manual”=>1); // HASH
echo $books[“perl manual”]; // output: 1
$books[“lisp manual”] = 1; // Add a new element
Arrays (II)
$books = array( ”php manual”,”perl manual”,”C manual”);
// Common loop
for ($i=0; $i < count($books); $i++)
print ($i+1).”-st book of my library: $books[$i]”;
each:
$books = array( “php manual”=>1,”perl manual”=>2,”C manual”=>3);
while ($item = each( $books )) // Retrieve items one by one
print $item[“value”].”-st book of my library: ”.$item[“key”];
// each retrieve an array of two elements with key and value of
current element
each and list:
while ( list($value,$key) = each( $books ))
print “$value-st book of my library: $key”;
// list collect the two element retrieved by each and store them
in two different // variables
Arrays (III)
Multidimensional arrays
$books = array( array(“title”=>“php manual”,”editor”=>”X”,”author”=>”A”),
array(“title”=>“perl manual”,”editor”=>”Y”,”author”=>”B”),
array(“title=>“C manual”,”editor”=>”Z”,author=>”C”));
Common loop
for ($i=0; $i < count($books); $i++ )
print “$i-st book, title: ”.$books[$i][“title”].
” author: “.$books[$i][“author”].“ editor: “.$books[$i][“editor”];
Use list and each
for ($i=0; $i < count($books); $i++) {
print “$i-st book is: “;
while ( list($key,$value) = each( $books[$i] ))
print “$key: $value ”;
print “<br/>”; // or “\n”
}
Functions (I)
The syntax to implement a user-defined
function is :

function function_name([parameters-list]opt)
{……implementation code……}
- parameters-list: sequence of variables separated by “,”
- function names aren’t case-sensitive;
- to each parameter can be assigned a default value;
function function_name($param1,$param2=1,$param3=“string1”);
- arguments can be passed by value or by reference
It’s possible using a variable number of parameters
Functions (II)
Parameters by reference and by value:
<?
function test_function(&$by_reference,$by_value)
{
$by_reference += 10;
$by_value += 10;
return ‘any value’;
}
$by_ref = 10;
$by_value = 10;
$returned_string = test_function($by_ref,$by_value);
print “by_ref: $by_ref by_value: $by_value”;
print “returned value: $returned_string”;
// output by_ref: 20 by_value: 10
?>
PHP Editors and Development Suites
COMMERCIAL SOLUTIONS:

- Zend Studio (www.zend.com)


- NuSphere PHPEd (www.phped.com)

NON-COMMERCIAL SOLUTIONS:

- PHPEdit (www.phpedit.net)
- Davor's PHP Editor ()

Search for editors and IDEs:

- http://www.thelinuxconsultancy.co.uk/phpeditors/
PHP & Mysql
- PHP 4 support directly MySQL, including libraries with functions to
connect and send receive data with a MySQL server. Compiling PHP is
enough to request the mysql support

#./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

- PHP 5 can be compiled with MySQL support but mysql libraries are no
longer included in PHP distribution. Compiling PHP must specify the
location of mysql libraries

#./configure --with-apxs2=/usr/local/apache2/bin/apxs \
--with-mysql=/usr/local/mysql

- Using support in Linux distribution or rpm packages all can be installed


in a single command
PHP Mysql functions (I)
PHP compiled with MySQL support includes a complete set of functions to
access mysql databases:
mysql_affected_rows -- Get number of affected rows in previous MySQL operation
mysql_change_user -- Change logged in user of the active connection
mysql_client_encoding -- Returns the name of the character set
mysql_close -- Close MySQL connection
mysql_connect -- Open a connection to a MySQL Server
mysql_create_db -- Create a MySQL database
mysql_data_seek -- Move internal result pointer
mysql_db_name -- Get result data
mysql_db_query -- Send a MySQL query
mysql_drop_db -- Drop (delete) a MySQL database
mysql_errno -- Returns the numerical value of the error message from previous MySQL operation
mysql_error -- Returns the text of the error message from previous MySQL operation
mysql_escape_string -- Escapes a string for use in a mysql_query.
mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both.
mysql_fetch_assoc -- Fetch a result row as an associative array
mysql_fetch_field -- Get column information from a result and return as an object
mysql_fetch_lengths -- Get the length of each output in a result
mysql_fetch_object -- Fetch a result row as an object
mysql_fetch_row -- Get a result row as an enumerated array
mysql_field_flags -- Get the flags associated with the specified field in a result
...
...
PHP Mysql functions (II)
mysql_field_len -- Returns the length of the specified field
mysql_field_name -- Get the name of the specified field in a result
mysql_field_seek -- Set result pointer to a specified field offset
mysql_field_table -- Get name of the table the specified field is in
mysql_field_type -- Get the type of the specified field in a result
mysql_free_result -- Free result memory
mysql_get_client_info -- Get MySQL client info
mysql_get_host_info -- Get MySQL host info
mysql_get_proto_info -- Get MySQL protocol info
mysql_get_server_info -- Get MySQL server info
mysql_info -- Get information about the most recent query
mysql_insert_id -- Get the ID generated from the previous INSERT operation
mysql_list_dbs -- List databases available on a MySQL server
mysql_list_fields -- List MySQL table fields
mysql_list_processes -- List MySQL processes
mysql_list_tables -- List tables in a MySQL database
mysql_num_fields -- Get number of fields in result
mysql_num_rows -- Get number of rows in result
mysql_pconnect -- Open a persistent connection to a MySQL server
mysql_ping -- Ping a server connection or reconnect if there is no connection
mysql_query -- Send a MySQL query
mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement,
taking into account the current charset of the connection.
mysql_result -- Get result data
mysql_select_db -- Select a MySQL database
mysql_stat -- Get current system status
mysql_tablename -- Get table name of field
mysql_thread_id -- Return the current thread ID
mysql_unbuffered_query -- Send an SQL query to MySQL, without fetching and buffering the result rows
Networking details
Depending of the project a good networking design is needed to have good
benchmarks. Different scenarios are possible:

- A single server Hosting Web Server (with PHP) and MySQL


- One host for Web Server (with PHP) and a second host for MySQL
- You must check the transfer rate and the speed of the connection
- You must grant enough permission to access MySQL from PHP but taking
care of security issue
- You need to encrypt data if the path from the Web Server to MySQL is not
completely in a trusted environment
- Many Server with MySQL
- One server must be the primary, the others are slave
- Every Web Server will do read-only queries into the nearest MySQL server
- Every slave server must be properly configured to replicate the Master
Server databases
- Every modification to the database must be done to the Master Server
Database requirements
MySQL in always under strong development. Planning your
application you need to find out if the last stable version has
all the functionalities you need from the database.
- Foreign keys (from 3.23.44 with InnoDB tables)
Allows to automatically check for referential integrity executing
specific tasks after the modification of foreign keys

- Transactions (3.23 Max and all >4.0 with InnoDB tables)


Allows to execute a set of tasks like an unique atomic action

- Hidden queries (4.1)


Allows to retrieve data with more complex queries on more than
one level

- Triggers, Views, Stored Procedures, etc... (5.0 now stable)


Create the database
Let’s suppose PHP and MySQL are
installed and working. Now we can
create the working db, one possibility
#mysq –u root –p is from the console (or from
Enter password:####
phpMyAdmin)

mysql>create database weben_2005

mysql>use weben_2005

mysql>CREATE TABLE personnel (

>fistname varchar(25),

>lastname varchar(20),

>nick varchar(12),

>salary int);

mysql>INSERT INTO personnel VALUES (’Marc’,’Maverick’,’Mav’,’20000’);

mysql>INSERT INTO personnel VALUES (’John’,’Vinny’,’Jo’,’35000’);


phpMyAdmin
http://www.phpmyadmin.net/home_page/

Easy to install, is a PHP application used like an intranet tool.


Un compress the tar.bz2 file into your document root:

#tar jxvf phpMyAdmin-2.6.4-pl3.tar.bz2

Rename the directory:


#mv phpMyAdmin-2.6.4-pl3 phpmyadmin

Then edit phpmyadmin/config.inc.php to match your MySQL parameters


(server address, user, password etc...)

Then access your MySQL databases using a browser.

If you don’t have virtual domains the address is:

http://localhost/phpmyadmin/index.php
View the database from a PHP script
<html>
<?php // view_table.php
$db = mysql_connect(“localhost”,”guest”,””);
if (!mysql_select_db('weben_2005',$db))
die('Error selecting Database!');
$result = mysql_query(“SELECT * FROM personnel”,$db);
echo “<table>”;
echo “<tr><td><b>Full Name</b></td><td><b>Nick Name</b></td>
<td><B>Salary</b></td></tr>”;
while ($myrow = mysql_fetch_array($result)) {
echo “<tr><td>”;
echo $myrow[“firstname”];
echo “ “;
echo $myrow[“lastname”];
echo “</td><td>”;
echo $myrow[“nick”];
echo “</td><td>”;
echo $myrow[“salary”];
echo “</td></tr>”;
}
echo “</table>”;
?>
<br/><a href=’add_table.php’>Insert New Element</a></html>
view_table.php The output
Full Name Nick Name Salary
Mark Maveric Mav 20000
John Vinny Jo 35000

<html>
<table>
<tr>
<td><b>Full Name</b></td>
<td><b>Nick Name</b></td>
<td><B>Salary</b></td>
</tr>
<tr>
<td>Mark Maverick</td>
<td>Mav<td>20000<tr><td>John Vinny</td>
<td>Jo</td>
<td>35000</td>
</tr>
</table>
</html>
Database connection
mysql_connect() try to create the connection to a MySQL
database server. Let’s see the online php reference
(www.php.net)
$db = mysql_connect(“localhost”,”guest”,””);
Select the correct DB
After the correct connection to the DB, mysql_select_db()
allows to select the requested DB.
mysql_select_db('weben_2005',$db)
Query the database
Line 5: mysql_query() sends a SELECT to the database to
retrieve data
$result = mysql_query(“SELECT * FROM personnel”,$db);
Retrieve data
Line 9: mysql_fetch_array() sends a SELECT to the
database to retrieve data
while ($myrow = mysql_fetch_array($result)) {}
view_table.php output
Adding new Records to DB
We sow how to view records, now let’s add new records. First we’ll create
a static form
<html>

<body>

<form method=“post” action=“datain.php”>

First name:<input type=“Text” name=“first”><br>

Last name:<input type=“Text” name=“last”><br>

Nick Name:<input type=“Text” name=“nickname”><br>

Salary:<input type=“Text” name=“salary”><br>

<input type=“Submit” name=“submit” value=“Enter Information>

</form>

</html>
Insert data
Just compile all fields, then submit data pressing “Enter
Information” button

Now we have a form that will post the information to a page “datain.php”.
We must code this page so that it is able to process the posted data and
send it to our MySQL database.
<html> Collect and save data (datain.php)
<?php

$db = mysql_connect("localhost","guest",”mypwd");

mysql_select_db("learndb",$db);

$sql = "INSERT INTO personnel (firstname,lastname,nick,salary)


VALUES(‘”.$_POST[“first”].”',‘”.$_POST[“last”].”',‘”.

$_POST[“nickname”].”',‘”.$_POST[“salary”].')";

if ($result = mysql_query($sql))

echo “Thank you!Entry correctly added.<br/>”;

else

echo “Error executing query ‘$sql’<br/>”;

?>

<br/><a href='view_table.php'>View Table</a>

</html>
datain.php output
After the submit, the destination script is executed, the output
message just display that everything has been saved
view data again
Now we just verify the correct execution of INSERT statement
POST and GET
Variables sent to Apache using a POST form are accessible by PHP code using
the array $_POST
<form method=“post” action=“datain.php”>

First name:<input type=“Text” name=“first”><br>

Last name:<input type=“Text” name=“last”><br>

Get variables are accessed by PHP using $_GET array


http://domain/myscript.php?var1=string1&var2=string2&var3=string3

$_GET[‘var1’] = string1;
$_GET[‘var2’] = string2;
$_GET[‘var3’] = string3;

Easy to install, is a PHP application used like an intranet tool.


Un compress the tar.bz2 file into your document root:
viewdb2.php
1: <html>

2: <?php // viewdb2.php

3: $db = mysql_connect("localhost","root","mypwd");

4: mysql_select_db("learndb",$db);

5: $result = mysql_query("SELECT * FROM personnel",$db);

6: echo "<table border=2>";

7: echo "<tr><td><b>Full Name</b></td><td><b>Nick Name</b></


td><td><b>Options</b></td></tr>";

8: while ($myrow = mysql_fetch_array($result)) {

9: echo "<tr><td>".$myrow["firstname"]." ".$mysql["lastname"]."</td><td>".$myrow["nick"];

10: echo "</td><td><a href=\"view.php?id=".$myrow[id]."\">View</a></td></tr>";

11: }

12: echo "</table>";

13: ?>

14: <br/><a href='add_table.php'>Insert New Element</a></html>


Adding a unique ID (I)
Using phpMyAdmin we add a new unique int ID:

- from table structure select add new field at the beginning of the table

- insert the name “id”


just a common way to call the id, other stadard is: personnel_id

- select type INT, specify Unsigned


We just need a positiv integer

- Specify PRIMARY KEY


I means it will be a Unique identifier for every record

- Specify Auto_increment
When a new record is inserted MySQL automatically assign to id the
last id+1

- Then Click SAVE


Adding a new ID (II)
Now let us see the difference using the Table Dump,
follows the structure and all records:
CREATE TABLE `personnel` (
`id` int(10) unsigned NOT NULL auto_increment,
`firstname` varchar(60) NOT NULL,
`lastname` varchar(100) NOT NULL,
`nick` varchar(20) NOT NULL,
`salary` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `personnel`
--
INSERT INTO `personnel` VALUES (1, 'Mark', 'Maveric', 'Mav', 20000);
INSERT INTO `personnel` VALUES (2, 'John', 'Vinny', 'Jo', 35000);
INSERT INTO `personnel` VALUES (3, 'Simone', 'Grassi', 'simo', 15000);
viewdb2.php
This is the output. Some data is displayed in the
table, then an Option row is added to reach more
informations

http://localhost/weben_2005/examples/view.php?id=1
View a single record: view.php
View accept the id to retrieve (GET). Retrieve data about this
Entry, then display values to the browser.

1: <html>
2: <?php // view.php
3: $db = mysql_connect("localhost","guest","mypwd");
4: mysql_select_db("learndb",$db);
5: $result = mysql_query("SELECT * FROM personnel
WHERE id=".$_POST["id"],$db);
7: $myrow = mysql_fetch_array($result);
8: echo "First Name: ".$myrow["fistname"];
9: echo "<br>Last Name: ".$myrow["lastname"];
10: echo "<br>Nick: ".$myrow["nick"];
11: echo "<br>Salary: ".$myrow["salary"];
12: ?>
13: <br/><a href='viewdb2.php'>Go Back to Table</a></html>
View.php output

Mysql_fetch_array cannot retrieve data, $result is


not a valid MySQL result resource
Find the mistake
We know that there is an error retrieving data, in
line 6. But usually must take care of:

Line 2: Check if the connection is correct


Line 3: Check if the db is correctly selected
Line 5: Check if the query is correctly executed
Line 6: Check if data is retrieved
1: <html> query string was ok but the result was empty
2: <?php // view.php

3: $db = mysql_connect("localhost","guest","mypwd");

4: mysql_select_db("learndb",$db);

5: $result = mysql_query("SELECT * FROM personnel

WHERE id=".$_GET["id"],$db);

// Was POST, but we receive data by GET

7: $myrow = mysql_fetch_array($result);

8: echo "First Name: ".$myrow["fistname"];

9: echo "<br>Last Name: ".$myrow["lastname"];

10: echo "<br>Email address: ".$myrow["email"];

11: echo "<br>Salary: ".$myrow["salary"];

12: ?>

13: </html>
Correct output
The query is correct and the relative output
Separating HTML & PHP
FIRST STEP: PRINTING HTML FROM PHP
- As PHP Novice in year 2000 I started my first PHP script. It was
amazing how easy was to create dynamic HTML pages

- After a while it’s easy to understand how crazy and complicated


could become a file with PHP and HTML tags
SECOND STEP: USING TEMPLATES TO SEPARATE PHP FROM
HTML

<?php ?>
html+php Template engine*
html
* Smarty is a known and widely used template engine
<?php
Smarty crash course
include('Smarty.class.php');
// create object
$smarty = new Smarty;
// assign some content. This would typically come from
// a database or other source, but we'll use static
// values for the purpose of this example.
$smarty->assign('name', 'george smith');
$smarty->assign('address', '45th & Harris');
// display it
$smarty->display('smarty.tpl');
?> TEMPLATE AFTER
TEMPLATE BEFORE (output HTML)
(smarty.tpl)
<html>
<html>
<head>
<head>
<title>User Info</title>
<title>User Info</title>
</head>
</head>
<body>
<body>
User Information:<p>
User Information:<p>
Name: george smith<br>
Name: {$name}<br>
Address: 45th & Harris<br>
Address: {$address}<br>
</body>
</body>
</html>
</html>
Smarty crash course (II)
line 2: Smarty must be included to be used
line 4: Instantiate Smarty object to be able to use methods/functions
line 8: assign API tells Smarty to substitute a tag with a string
line 9: a second assignment for the second variable
line 11: finally another API is called to render the template and obtain
the output string.

1:<?php
2:include('Smarty.class.php');
3:// create object
4:$smarty = new Smarty;
5:// assign some content. This would typically come from
6:// a database or other source, but we'll use static
7:// values for the purpose of this example.
8:$smarty->assign('name', 'george smith');
9:$smarty->assign('address', '45th & Harris');
10:// display it
11:$smarty->display('smarty.tpl');
12:?>
Smarty crash course (III)
What we obtained?

- Graphical User Interface (HTML) is separated from code


- All files can be collected into a specific directory
- Team work can be better separated. Professionals about graphics
just care about graphical requests, then from the created template
is created the template file for the specific template engine (like
smarty)
- Not only the content is dynamic but also some graphical
adjustments
- The business logic can be changed without care about how the
output is displayed (not always 100% true)
PHP + MySQL + templating
Enabling web technologies is fast and easy with PHP, but becomes
fastly hardly to manage:

- big script with HTML mixed with PHP


- very difficult to maintain
- very time consuming to upgrade or change due to new requirements
- many scripts (sometimes written by different developers with
different styles)

Adding templating to PHP and MySQL the content is separated from


the GUI, and just “plugged-in” with a template engine.
BUT IS NOT ENOUGHT TO LET PHP/MySQL BE READY FOR BIG
PROJECTS (ex: enterprise solutions)
- Business logic must be decoupled from data retrieving
- Configuration/Deployment must be made easy and easily
reconfigurable
- Component programming is a must, this can be realized using
Object Oriented Programming and Pattern Design reuse.
<?php
class Cart {
Object Oriented PHP4
var $items; // Items in our shopping cart

// Add $num articles of $artnr to the cart

function add_item($artnr, $num) {


$this->items[$artnr] += $num;
}

// Take $num articles of $artnr out of the cart

function remove_item($artnr, $num) {


if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true; A class is a collection of
} else {
return false; variables and functions working
} with these variables. A class is
} defined using the following
} syntax:
?>
OO Example
Now we use the Cart the class:

1: <?php
2: $cart = new Cart;
3: $cart->add_item("10", 1);
4: $another_cart = new Cart;
5: $another_cart->add_item("0815", 3);
6: ?>

line 2: we ISTANTIATE the class, obtaining an istance in variable $cart

line 3: we use method add_item to add an item to the cart

line 4: we “create” a new Cart, storing the reference in variable $another_cart

line 5: using method add_item we add an item to the second cart


Now we use inheritance to extend out
class, adding new functionalities
OO Example (II)
1: <?php
2: require(‘Cart.php’);
3: class Named_Cart extends Cart {
4: var $owner;
5: function set_owner ($name) {
6: $this->owner = $name;
7: }
8: }
9: ?>

line 2:We require another file, the one containing the class Cart

line 3: A new class is defined as an extension of existing Cart

line 4: another variable is specified

line 5: another method is specified

line 6: $this is a reference to the current object


OO Example (III)
1: <?php
2: require(‘Named_Cart.php’);
3: $ncart = new Named_Cart;
4: $ncart->set_owner("kris");
5: print $ncart->owner;
6: $ncart->add_item("10", 1);
7: ?>

line 2: We require the file containing the new cart class

line 3: Create a named cart istance

line 4: print the Cart owner name

line 5: add an item using inherited method from cart class


Abstraction Layers
The abstraction layer decouple the above layer from
the layer below making transparent the change of
one of them to the other of them.
In PHP development a good DB Abstraction layer
php script
allows the PHP script not to care about the Data
Access. Using PEAR::DB, allows the canche to
change the Database canching any line of the php
script.

php script
A.Layer

Data access
Data access
DB Abstraction Layers
an example!
<?php
require_once 'DB.php';
$db = DB::connect('mysql://user:pw@host/mydb');
$stmt = $db->prepare('SELECT * FROM comments');
$result = $db->execute($stmt);
while($row = $db->fetchrow($result)) {
while($row as $field => $value ) {
echo "$field: $value<br>\n";
}
}
$db->disconnect();
?>
Abstracting the abstraction
We sow how to use PEAR::DB as Database Abstraction Layer. After
some time develping with PEAR::DB you understand that:

- Many piece of code are used and reused many times


- All this code is easily copies & pasted but some environmental
differences makes the maintenance more difficult
- when you find a smarted approach in solving a problem, if you need
to use it in all your scripts you need to do it in all of them (usually not
easy to do with search & replace features, due to small changes in
variable names, and anyway not reliable)

The solutions is to create another abstraction layer addressing all this


needed functionalities. We will use PEAR::DB_DataObject
DB_DataObject
DataObject allows to speed-up example.php
development in different ways:

- creating automatically PHP code. It


creates a new script containing a class for
each table
- creating abstract Application DB_DataObject*
Programming Interfaces (API) on top of PEAR::DB
PEAR::DB API to simplify developers life

(* DB_DataObject uses not only PEAR::DB


Interfaces but also object extension
features)
Data access
DB_DataObject configuration (I)
Create a DataObject folder into your script folder, and save a file called
db_dataobject.ini there. An example follows:

[DB_DataObject]
; PEAR::DB DSN
database = mysql://user:pwd@db_server/db_name
;sitepoint.ini schema location
schema_location = /var/www/html/weben_2005/examples/DataObject
;Location where DataObject classes will be created
class_location = /var/www/html/weben_2005/examples/DataObject
; Prefix for including files from your code
require_prefix = weben_2005/examples/DataObject
;Classes should be prefixed with this string
class_prefix = DataObject_
;Debugging information: 0=off, 1=display sql, 2=display results,3=everything
debug = 0
;Prevent SQL Insert, Update and Delete from being performed
debug_ignore_updates = false
;Whether to die of error with a PEAR_ERROR_DIE or not
dont_die = false
DB_DataObject configuration (II)
Now using the provided script, DataObject automatically creates the php
script containing one class for each database table:

- DataObject automatically discover the database structure


- for every table create a script containing a class

Put the Generator.php script into your examples/DataObject folder.


Then from the browser or on command line execute it:

localhost:~/htdocs/weben_2005/examples/DataObject$ php Generator.php


#!/usr/bin/php -q
db_dataobject_generator : 0 : CREATING FOR weben_2005

db_dataobject_generator : 0 : calling generatedefinitions


db_dataobject_generator : 0 : Generating Definitions file:
db_dataobject_generator : 0 : Writing ini as /var/www/html/weben_2005/examples/
DataObject/weben_2005.ini

db_dataobject_generator : 0 : calling generateclasses


db_dataobject_generator : 0 : writing DataObject_Personnel

db_dataobject_generator : 0 : DONE
DB_DataObject an example
We sow how to use PEAR::DB as Database Abstraction Layer. After
some time develping with PEAR::DB you understand that:
- Many piece of code are used and reused many times
- All this code is easily copies & pasted but some environmental
differences makes the maintenance more difficult
- when you find a smarted approach in solving a problem, if you need
to use it in all your scripts you need to do it in all of them (usually not
easy to do with search & replace features, due to small changes in
variable names, and anyway not reliable)

The solutions is to create another abstraction layer addressing all this


needed functionalities. We will use PEAR::DB_DataObject
PHP for “Big” projects
What’s a Big project? In my opinion when one or more of the following
conditions are true:

- Composed by a lot of code, >10.000 lines (without libraries)


- Involving at least a team or even more than a team
- Involving different professionals, design, development,
management, specific business specialist, customers
- Must be integrated into a system
- Other systems will need to interoperate with it
The need of a Frameworks
A framework allows a better planning of new projects and usually
allows a good separations in development tasks.

A php example is FastFrame, uses Object Oriented development


and Patter Design features to create a common environment for
application development.

Model View Control (MVC) paradigm is used that allow the separation
of the Model (mapping data access to php classes) to View (how data
are displayed into the Graphical User Interface) to Control (the business
logic specifically developed for the application)

Allows new developers to get used of a project with relative low start-up
time. An application developed without a good design (that usually means
relying on a framework) will be very difficult or impossible to be managed
by other developers without the presence of the original developers.
Learning path
- Script by script with Mixed HTML/PHP
- Template engine and library usage PHP<- Template ->HTML
- Object Oriented Programming maximizing code reuse and plugging
in open source libraries (try to do it by yourself and at the same time
see known solutions). In my opinion the best way to learn to reuse
code is wasting some time not reusing code.

- Learn Pattern Design for “2nd level” code reuse and add some
known Patterns to your code
- Learn and use a framework (ex: fastframe, that uses OOP and
Pattern Design) to create a complete web application

- Now all is moving is automatic code generation starting from models


(like UML or UML-style). There are already many Open Source
solutions (DataObject itself creates automatically the Data access
from the database scheme).
Bibliography
“Create dynamic sites with PHP & MySQL” by Md. Ashraful Anam
(www.codewalkers.com Resource for PHP and SQL Developers)

FastFrame http://www.codejanitor.com

PEAR: http://pear.php.net

PHP: http://www.php.net

MySQL: http://www.mysql.org

Вам также может понравиться