This document provides an overview of the PEAR DB abstraction layer. It allows for portable database programming in PHP by providing a common API that works across different database backends like MySQL, PostgreSQL, Oracle, etc. It handles tasks like prepared statements, transactions, error handling, and outputting query results in a standardized way. PEAR DB aims to simplify database programming and make applications less dependent on the underlying database system.
12. Slide 12Prepared 3/15/2016
What IS Apache, Anyway?
ďŹ Open-Source Web server originally based on
NCSA server
ďŹ Available on over 160 varieties of Unix -- and
Windows NT
ďŹ Over 56% of Internet Web servers run Apache or
an Apache derivative
Graph copyright Netcraft (<http://www.netcraft.com/survey/>)
13. Slide 13Prepared 3/15/2016
Getting Apache
ďŹ You can pull the distribution down from
the Apache Web site
<http://www.apache.org/dist/>
ďŹ Some added-value vendors (e.g.,
RedHat) provide pre-built packaged
versions
ďŹ Some companies offer support (for a
price, of course!)
ďŹ The Apache site is mirrored all over the
world, so thereâs probably a site nearer to
you
14. Slide 14Prepared 3/15/2016
Configuring Apache
ďŹ Choosing functionality
â Apache functionality is available
through modules which are either built
into or loaded into the server
ďŹ Server instructions
â Apache reads its run-time configuration
instructions from text files
â No GUI available
â 182 configuration directives in base
package
15. Slide 15Prepared 3/15/2016
Configuring Apache
(continued)
ďŹ When used with -d option, server reads
httpd.conf; -f allows use of a different
name
ďŹ After httpd.conf, server reads
srm.conf, then access.conf (unless
the latter two have been renamed by
ResourceConfig and AccessConfig
directives, respectively)
ďŹ Consider combining these into a single
file for simplicity
16. Slide 16Prepared 3/15/2016
Virtual Hosts
ďŹ A single Apache server installation can
actually support hundreds of different
Web sites
ďŹ NSPs and ISPs do this a lot
ďŹ Allows additional Web presence without
accompanying hardware or software
investment required
17. Slide 17Prepared 3/15/2016
Content Negotiation
ďŹ If you have multiple language-specific
versions of documents, Apache can
automatically choose the correct one
according to the clientâs language
preferences
ďŹ Server can choose among different
graphics formats; if it has both GIF and
JPEG versions, it can send the one for
which the client has expressed a
preference
18. Slide 18Prepared 3/15/2016
Scripts, SSIs, Servlets, and
SSL
ďŹ Apache can handle run-time execution of
external applications (scripts)
ďŹ Server-side includes (SSIs) allow the
server to modify pages at run-time before
sending them
ďŹ Java servlet modules are available, but
not yet part of the base package (still
under development)
ďŹ SSL-enabled versions of Apache are
available, both from commercial vendors
and under open-source licence
19. Slide 19Prepared 3/15/2016
Logfiles
ďŹ Two basic logfiles
â Access log -- whoâs been visiting your
server and what they wanted
â Error log -- problems the server has
encountered and things it has noticed
ďŹ Can be configured for each virtual host,
or for entire server
ďŹ Access log format can be customised
20. Slide 20Prepared 3/15/2016
Improving Performance
ďŹ Have enough physical memory
â Apache works best when it doesnât
need to swap
â Use MaxClients to limit concurrent
requests to a rational and supportable
value
ďŹ Have fast enough hardware
â CPU, disk, network interface
ďŹ Donât use NFS! And definitely not for
your ServerRoot or logfile directories
21. Slide 21Prepared 3/15/2016
Improving Performance
(continued)
ďŹ Reduce filesystem lookups
â Looking for and opening .htaccess
files is expensive; apply
AllowOverrides None liberally
â Organise document tree to minimise
cache thrash
â Donât enable symbolic link tracing (omit
FollowSymLinks and
SymLinksIfOwnerMatch from
Options directives)
22. Slide 22Prepared 3/15/2016
Improving Performance
(continued)
ďŹ Disable DNS lookups with
HostNameLookups Off except where
needed (in ScriptAlias directory,
<Files .cgi>, et cetera)
ďŹ Restrict content negotiation; only enable
Options MultiViews where needed,
and use DirectoryIndex x y z with
the most common choices listed first
ďŹ Consider increasing the value of
MaxRequestsPerChild unless base
child memory consumption is large or
there is danger of memory leaks
23. Slide 23Prepared 3/15/2016
Improving Performance
(continued)
ďŹ Use mod_status to monitor server
children; tune StartServers,
MinSpareServers, and
MaxSpareServers accordingly -- but
IFF indicated
ďŹ Consider adjusting KeepAliveTimeout if
keptalive connexions arenât likely (e.g.,
simple pages without inlined images)
ďŹ Donât use SSIs except where needed
24. Slide 24Prepared 3/15/2016
Going Further
ďŹ The main Apache site
http://www.apache.org/
ďŹ HTML Syntax Validator
http://validator.w3.org/
ďŹ CGI Specification:
http://www.w3.org/pub/WWW/CGI/
ďŹ CGI RFC project:
http://Web.Golux.Com/coar/cgi/
ďŹ USENET News:
comp.infosystems.www.servers.unix
26. Brief History of PHP
PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in
1994. It was initially developed for HTTP usage logging and server-side
form generation in Unix.
PHP 2 (1995) transformed the language into a Server-side embedded
scripting language. Added database support, file uploads, variables,
arrays, recursive functions, conditionals, iteration, regular expressions,
etc.
PHP 3 (1998) added support for ODBC data sources, multiple platform
support, email protocols (SNMP,IMAP), and new parser written by Zeev
Suraski and Andi Gutmans .
PHP 4 (2000) became an independent component of the web server for
added efficiency. The parser was renamed the Zend Engine. Many
security features were added.
PHP 5 (2004) adds Zend Engine II with object oriented programming,
robust XML support using the libxml2 library, SOAP extension for
interoperability with Web Services, SQLite has been bundled with PHP
27. Brief History of PHP
As of August 2004, PHP is used on 16,946,328 Domains, 1,348,793 IP
Addresses http://www.php.net/usage.php This is roughly 32% of all
domains on the web.
28. Why is PHP used?
1. Easy to Use
Code is embedded into HTML. The PHP code is enclosed in special start and
end tags that allow you to jump into and out of "PHP mode".
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
29. Why is PHP used?2.Cross Platform
Runs on almost any Web server on several operating systems.
One of the strongest features is the wide range of supported
databases
Web Servers: Apache, Microsoft IIS, Caudium,
Netscape Enterprise Server
Operating Systems: UNIX (HP-
UX,OpenBSD,Solaris,Linux), Mac OSX, Windows
NT/98/2000/XP/2003
Supported Databases: Adabas D, dBase,Empress,
FilePro (read-only), Hyperwave,IBM DB2, Informix,
Ingres, InterBase, FrontBase, mSQL, Direct MS-
SQL, MySQL, ODBC, Oracle (OCI7 and OCI8),
Ovrimos, PostgreSQL, SQLite, Solid, Sybase,
Velocis,Unix dbm
30. Getting Started
1. How to escape from HTML and enter PHP mode
⢠PHP parses a file by looking for one of the special tags that
tells it to start interpreting the text as PHP code. The parser then
executes all of the code it finds until it runs into a PHP closing tag.
Starting tag Ending tag Notes
<?php ?> Preferred method as it allows the use of
PHP with XHTML
<? ?> Not recommended. Easier to type, but has
to be enabled and may conflict with XML
<script language="php"> ?> Always available, best if used when
FrontPage is the HTML editor
<% %> Not recommended. ASP tags support was
added in 3.0.4
<?php echo âHello Worldâ; ?>
PHP CODE HTMLHTML
31. Getting Started
2. Simple HTML Page with PHP
⢠The following is a basic example to output text using
PHP.
<html><head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body></html>
Copy the code onto your web server and save it as âtest.phpâ.
You should see âHello World!â displayed.
Notice that the semicolon is used at the end of each line of PHP
code to signify a line break. Like HTML, PHP ignores whitespace
between lines of code. (An HTML equivalent is <BR>)
32. Getting Started
3. Using conditional statements
⢠Conditional statements are very useful for displaying specific
content to the user. The following example shows how to display
content according to the day of the week.
<?php
$today_dayofweek = date(âwâ);
if ($today_dayofweek == 4){
echo âToday is Thursday!â;
}
else{
echo âToday is not Thursday.â;
}
?>
33. Getting Started
3. Using conditional statements
The if statement checks the value of $today_dayofweek
(which is the numerical day of the week, 0=Sunday⌠6=Saturday)
⢠If it is equal to 4 (the numeric representation of Thurs.) it will display
everything within the first { } bracket after the âif()â.
⢠If it is not equal to 4, it will display everything in the second { } bracket
after the âelseâ.
<?php
$today_dayofweek = date(âwâ);
if ($today_dayofweek == 4){
echo âToday is Thursday!â;
}
else{
echo âToday is not Thursday.â;
}
?>
34. Getting Started
3. Using conditional statements
If we run the script on a Thursday, we should see:
âToday is Thursdayâ.
On days other than Thursday, we will see:
âToday is not Thursday.â
<?php
$today_dayofweek = date(âwâ);
if ($today_dayofweek == 4){
echo âToday is Thursday!â;
}
else{
echo âToday is not Thursday.â;
}
?>
35. Examples
⢠Step 1: Universal header and footer in a single file
⢠Create a file called header.php. This file will have all of the
header HTML code. You can use FrontPage/Dreamweaver to create the
header, but remember to remove the closing </BODY> and </HTML> tags.
<html><head>
<title>UCR Webmaster Support Group</title>
<link rel="stylesheet" type="text/css" href=âmycssfile.css">
</head>
<body>
<table width=80% height=30>
<tr><td>
<div align=center> Page Title </div>
</td></tr></table>
36. Examples
⢠Step 2: Universal header and footer in a single file
⢠Next, create a file called footer.php. This file will have all of the footer HTML
code.
<table width=80% height=30>
<tr><td>
<div align=center> UC Riverside Department<BR>
<a
href=mailto:someuser@ucr.edu>someuser@ucr.edu</a>
</div>
</td></tr></table>
</body>
</html>
37. Examples
⢠Step 3: Universal header and footer in a single file
⢠This is the basic template that you will use on all of the pages. Make sure you name the
files with a .php extension so that the server will process the PHP code. In this example,
we assume the header and footer files are located in the same directory.
<?php
// header
include(âheader.phpâ);
?>
Insert content here!
<?php
// footer
include(âfooter.phpâ);
?>
38. Examples
Benefits:
- Any changes to header or footer only require editing of a
single file. This reduces the amount of work necessary for
site maintenance and redesign.
- Helps separate the content and design for easier maintenance
Page 1
Content
Page 5
Content
Page 3
Content
Page 2
Content
Page 4
Content
Header
Footer
39. Examples
⢠Step 1: Simple Page Counter
⢠Download the counter file webcounter.txt onto your machine
⢠Upload the webcounter.txt file onto your web server (via FTP, WinSCP, etc)
⢠Change the file permissions of the webcounter.txt file to 777 to allow the
counter file to be updated.
40. Examples
⢠Step 2: Simple Page Counter
⢠Copy this code into a page where you want a counter.
<?php
$COUNTER_FILE = âwebcounter.txt";
if (file_exists($COUNTER_FILE)) {
$fp = fopen("$COUNTER_FILE", "r+");
flock($fp, 1);
$hits = fgets($fp, 4096);
$hits += 1;
fseek($fp,0);
fputs($fp, $hits);
flock($fp, 3);
fclose($fp);
}
?>
41. Examples
⢠Step 3: Simple Page Counter
⢠Next, output the counter value using PHP.
Copy this line after the main block of code.
This page has been viewed <?php echoâ$hitsâ; ?> times.
⢠Thatâs it! The result should look something similar to:
42. Examples
⢠Step 3: Simple Page Counter
⢠You can change the text around the
<?php echoâ$hitsâ; ?> tags to your liking.
<?php echoâ$hitsâ; ?> visitors.
This example shows
1. How to escape from HTML and enter PHP mode
2. How to output variables onto the screen using PHP
43. Examples
2. How to output variables using PHP
⢠Echo is the common method in outputting data. Since it
is a language construct, echo doesnât require parenthesis
like print().
⢠Output Text Usage:
<?php echo âHello Worldâ; ?> // prints out Hello World
⢠Output the value of a PHP variable:
<?php echo â$hitsâ; ?> // prints out the number of hits
⢠Echo has a shortcut syntax, but it only works with the âshort
open tagâ configuration enabled on the server. <?= $hits ?>
44. Examples
3. Other uses with echo()
⢠Automatically generate the year on your pages. This will
print out Š2004 UC Riverside.
Š<?php echo date(âYâ); ?> UC Riverside
⢠You will need to escape any quotation marks with a backslash.
<?php echo âI said âShe sells sea shellsâ â; ?>
45. WHAT is PEAR
The PHP Extension and Application Repository, or PEAR,
is a framework and distribution system for PHP code components.
Stig S. Bakken founded the PEAR project in 1999 to promote the re-
use of code that performs common functions.
The project has the goals of:
⢠providing a structured library of code
⢠maintaining a system for distributing code and for managing code
packages
⢠promoting a standard coding-style
46. ⢠Table.php allows you to generate HTML table
without the need to include HTML tags in your
PHP code.
⢠PHP code is easier to read.
⢠PHP code is shorter.
⢠PHP code is easier to maintain.
⢠Its usage is very easy.
⢠Tables can be modified at any time.
⢠The logic is the same as standard HTML editors.
47.
48.
49.
50.
51.
52.
53.
54.
55. PEAR DB
DB is a database abstraction layer providing:
* an OO-style query API
* portability features that make programs written for one DBMS work with other
DBMS's
* a DSN (data source name) format for specifying database servers
* prepare/execute (bind) emulation for databases that don't support it natively
* a result object for each query response
* portable error codes
* sequence emulation
* sequential and non-sequential row fetching as well as bulk fetching
* formats fetched rows as associative arrays, ordered arrays or objects
* row limit support
* transactions support
* table information interface
* DocBook and phpDocumentor API documentation
56. The currently supported database back ends are:
⢠dbase -> dBase
⢠fbsql -> FrontBase (functional since DB 1.7.0)
⢠ibase -> InterBase (functional since DB 1.7.0)
⢠ifx -> Informix
⢠msql -> Mini SQL (functional since DB 1.7.0)
⢠mssql -> Microsoft SQL Server (NOT for Sybase. Compile PHP --with-mssql)
⢠mysql -> MySQL (for MySQL <= 4.0)
⢠mysqli -> MySQL (for MySQL >= 4.1) (requires PHP 5) (since DB 1.6.3)
⢠oci8 -> Oracle 7/8/9
⢠odbc -> ODBC (Open Database Connectivity)
⢠pgsql -> PostgreSQL
⢠sqlite -> SQLite
⢠sybase -> Sybase
57. How to install PEAR DB
PEAR DB is compatible with PHP 4 (version 4.0.4 or later) and PHP 5 but not
PHP 3.
The base PEAR installation included in the PHP distribution provides a
program named pear that lets you check what PEAR packages are installed.
To check whether the PEAR DB package is installed:
Do one of the following:
If you are using PHP 4.3.1 or later, run:
58. If DB is not listed in the command output, the package is not
installed.
If you are using PHP 4.3.1 or later, to install PEAR DB:
As root, run:
The pear command line installer opens an HTTP connection to the
PEAR package server, loads the package and then installs it on your
system.
59. Accessing PEAR DB Classes
To access the classes provided by the PEAR DB library, your PHP script
needs to include the file DB.php:
Using the require_once() statement ensures that DB.php will only be included
once even if other files that your script includes also reference DB.php.
Note that if you get the error Failed opening 'DB.php' for inclusion when running your
script, you need to edit your include_path directive to specify the directory where
DB.php is located. To do this, edit the include_path entry in your php.ini file. For
example, if DB.php is installed in /usr/share/pear:
include_path = ".:/php/includes:/usr/share/pear"
Note that on the platform we used for testing, Red Hat Linux, the default include_path
value already specified the DB.php location and so editing php.ini was not necessary.
To check the default value for include_path, use phpinfo().
Connecting to Databases through PEAR DB
60. To access a database through PEAR DB, you have to create a
data source name (DSN) that specifies the appropriate PEAR DB backend
for your database and the parameters necessary to connect to the
database.
DSN syntax:
phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value
for example: (mysql)
Connecting to Databases through PEAR DB
61. How to connect and disconnect
Connecting to Databases through PEAR DB
62. DB_common::query()
-- Sends a query to the database
DB_common::getAll()
-- Runs a query and returns all the data as an array
DB_common::getCol()
-- Runs a query and returns the data from a single column
DB_common::getAssoc()
-- Runs a query and returns the data as an array
DB_common::getOne()
-- Runs a query and returns the first column of the first row
DB_common::getRow()
-- Runs a query and returns the first row
Common PEAR DB Methods
63. Simple Web form
<html>
<head><title>simple form</title></head>
<body>
<form name="simpleForm" method="put"
action="simpleHandler.cgi">
Your email address:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
64. Forms
Forms are parts of an HTML document that users
can fill in. They may include buttons,
checkboxes, text areas, file selections.
The thing that users fill in are called the controls of
the form.
Some controls are hidden.
Controls are submitted to PHP in the form of
variables. Each control in the HTML form
becomes a variable in PHP. This is seen later.
65. <form>
This element encloses a form.
All form elements (discussed now) should be
children of the <form> element.
Technically can be more than one <form> in the
HTML page.
But it does not make much sense to have several
<form>s.
<form> accepts the core and i18n attributes. And it
has some other attributes. Some of these are
required.
66. the action= attribute of
<form>
It has a required action= attribute.
⢠The value of this attribute is the location
of a file that contains the action to
execute when the form is submitted.
⢠In our case, this will be the file name of
the PHP script that deals with the form
on wotan.
By default, scripts are executed using
return on the browser while a form
element has focus, or a special submit
button.
67. method= of <form>
<form> admits a method= attribute. This attribute
determines the http method by which the form is
submitted to the script. There are only two
realistic choices
⢠method="getâ (default)
⢠method="post"
When the form is submitted the http request line
that follows will have the method GET or POST.
Validation requires lowercase values.
68. method="get"
If you use GET, the form data is transmitted by
appending it to the URL of the script. Google's
Web search does it that way, for example.
There is a standard way to write the data in the
URL knows as Common Gateway Interface,
CGI. It is of no further interest to us.
Advantage: you can bookmark the form.
Problem: there is a limit of 1024 chars for the URL,
therefore only a limited information can be
transmitted in this way.
69. method="post"
If you use post, the user agent sends the form as a
POST message to the server.
The data is sent in the body of the http request.
Thus it can be as long as you want.
If you use POST you can set the MIME type of the
data with a special attribute enctype=
70. the type= attribute of <input/>
This attribute can only take the following values
⢠âtextâ enter text
⢠âpasswordâ enter text, but don't echo on screen
⢠âcheckboxâ enter checks on boxes
⢠âradioâ check one select
⢠âsubmitâ press to submit form
⢠âresetâ reset form
⢠âfileâ upload file (can only be done with
POST)
⢠âhiddenâ hidden form data, not shown
⢠âimageâ image map submission, not covered
71. the name= attribute of
<input/>
This give a name to the control that the users are
setting.
The script that is found by the action= attribute will
identify the controls by name. Therefore every
control should have a different name.
72. control name and PHP
variable
When the form is passed to the PHP script named
with the action= of the the <form> the controls
are accessible as PHP variables.
If name is the name of the control, and if the
method is POST, the control is read as the
variable $_POST['name'].
If name is the name of the control, and if the
method is GET, the control is read as the
variable $_GET['name'].
73. the size= attribute of <input/>
It lets you set the size of the input field.
Note that the size of the field may not limit the
input to that size.
When the type is âtextâ or âpasswordâ the value you
give to this field is the number of characters.
Otherwise it is the number of pixels.
74. example
HTML file greet.html has
<form action="greet.php" method="get"><p>
your last name: <input type="text"
name="lastname"/></p></form>
PHP file greet.php has
<?php
print "Hello ";
print $_GET['lastname'];
?>
in addition to the usual HTML stuff.
75. the push button <button>
This makes a button for decoration.
It takes a type= attribute that can be either be
'button', 'submit' or 'reset'.
It has takes a name= attribute for the name of the
control that it sets.
It takes a value= attribute attribute to set a value.
It also takes the core and i18n attributes.
And it can have character contents!
I am not sure what it is good for.
76. summary
Forms deliver data to the server. The server can
then process the data and deliver a response.
Active effects can also be done client-side. This is
done using the <script> element that mostly
uses a language called javascript.