PHP and Mysql Slides
PHP and Mysql Slides
Examples
Simone Grassi
PhD at Trinity College Dublin
Research on Software Architectures
Distributed Systems Group
[email protected]
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:
$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);
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:
NON-COMMERCIAL SOLUTIONS:
- PHPEdit (www.phpedit.net)
- Davor's PHP Editor ()
- 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
- 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
mysql>use weben_2005
>fistname varchar(25),
>lastname varchar(20),
>nick varchar(12),
>salary int);
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>
</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);
$_POST[“nickname”].”',‘”.$_POST[“salary”].')";
if ($result = mysql_query($sql))
else
?>
</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”>
$_GET[‘var1’] = string1;
$_GET[‘var2’] = string2;
$_GET[‘var3’] = string3;
2: <?php // viewdb2.php
3: $db = mysql_connect("localhost","root","mypwd");
4: mysql_select_db("learndb",$db);
11: }
13: ?>
- from table structure select add new field at the beginning of the table
- Specify Auto_increment
When a new record is inserted MySQL automatically assign to id the
last id+1
--
-- 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
3: $db = mysql_connect("localhost","guest","mypwd");
4: mysql_select_db("learndb",$db);
WHERE id=".$_GET["id"],$db);
7: $myrow = mysql_fetch_array($result);
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
<?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?
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 require another file, the one containing the class Cart
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:
[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:
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)
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
FastFrame http://www.codejanitor.com
PEAR: http://pear.php.net
PHP: http://www.php.net
MySQL: http://www.mysql.org