Installing PEAR on Windows Next you need to install PEAR’s database helper package, called MDB2, by typing in the following see Figure E-2: pear install MDB2 Figure E-2.. Installing the
Trang 1WEEKDAY(date)
Returns the weekday index for date where 0=Monday through 6=Sunday This code returns
the value 1:
SELECT WEEKDAY('2006-04-04');
Time Functions
Sometimes you need to work with the time, rather than the date, and MySQL provides plenty of functions for you to do so
CURTIME()
CURTIME()
Returns the current time as a value in the format HH:MM::SS or HHMMSS.uuuuuu, de-pending on whether the function is used in a string or numeric context The value is expressed using the current time zone When the current time is 11:56:23, this code returns the values 11:56:23 and 11:56:23.000000:
SELECT CURTIME() + 0;
HOUR()
HOUR(time)
Returns the hour for time This code returns the value 11:
SELECT HOUR('11:56:23');
MINUTE()
MINUTE(time)
Returns the minute for time This code returns the value 56:
SELECT MINUTE('11:56:23');
SECOND()
SECOND(time)
Returns the second for time This code returns the value 23:
SELECT SECOND('11:56:23');
SECOND() | 471
Trang 2MAKETIME(hour, minute, second)
Returns a time value calculated from the hour, minute, and second arguments This code
returns the time 11:56:23:
SELECT MAKETIME(11, 56, 23);
TIMEDIFF()
TIMEDIFF(expr1, expr2)
Returns the difference between expr1 and expr2 (expr1 – expr2) as a time value Both expr1 and expr2 must be TIME or DATETIME expressions of the same type This code returns the value 01:37:38:
SELECT TIMEDIFF('2000-01-01 01:02:03', '1999-12-31 23:24:25');
UNIX_TIMESTAMP()
UNIX_TIMESTAMP([date])
If called without the optional date argument, this function returns the number of seconds since 1970-01-01 00:00:00 UTC as an unsigned integer If the date parameter is passed, then
the value returned is the number of seconds since the 1970 start date until the given date This code will return the value 946684800 (the number of seconds up to the start of the new millennium) followed by a TIMESTAMP representing the current Unix time at the moment you run it:
SELECT UNIX_TIMESTAMP('2000-01-01');
SELECT UNIX_TIMESTAMP();
FROM_UNIXTIME()
FROM_UNIXTIME(unix_timestamp [, format])
Returns the unix_timestamp parameter as either a string in YYYY-MM-DD HH:MM:SS or
YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a
string or numeric context If the optional format parameter is provided, the result is formatted
according to the specifiers in Table 8-17 This code returns the strings “2000-01-01 00:00:00” and “Saturday January 1st 2000 12:00 AM”:
SELECT FROM_UNIXTIME(946684800);
SELECT FROM_UNIXTIME(946684800, '%W %M %D %Y %h:%i %p');
472 | Appendix D: MySQL Functions
Trang 3APPENDIX E
Using PEAR and PHPUnit
If you’re going to use PHP as a web development language, why not make use of the wealth of packages that have already been written for it? The community has turned out in force to write an enormous amount of add-ons, a whole host of which have been combined in PEAR (the PHP Extension and Application Repository) Among these submissions is MDB2, a powerful package that makes it easier to access MySQL Ta-ble E-1 lists some of the PEAR packages
Table E-1 Categories of PEAR packages (number in each category)
Authentication (8) Filesystem (5) Math (19) Streams (2)
Caching (2) Gtk Components (4) Networking (55) Structures (30)
Console (7) Gtk2 Components (7) Numbers (2) System (8)
Database (31) HTML (40) Payment (4) Text (19)
Date and Time (22) HTTP (14) PEAR (18) Tools & Utilities (9)
Encryption (13) Images (19) PEAR Website (5) Validate (29)
Event (2) Internationalization (6) PHP (20) Web Services (40)
File Formats (33) Mail (8) Semantic Web (5) XML (32)
Installation
Installation of PEAR will vary according to which operating system you are using A Linux/Unix machine (especially if XAMPP has been installed on it as described in
Chapter 2) will generally be ready to go after issuing just a couple of commands But Windows and Mac OS X require a little more work
Windows
The EasyPHP setup that you installed in Chapter 2 comes packaged with a version of PEAR that you can install by selecting Start→Programs→Accessories and then right-clicking on the Command Prompt and choosing the “Run as Administrator” option You must have administrative privileges to install PEAR
473
Trang 4Now navigate to C:\Program Files\EasyPHP 3.0\php\, then run the batch file
go-pear.bat by typing the following (and then pressing Return):
go-pear
During installation, accept the defaults by pressing Return whenever you’re asked to
do something Figure E-1 shows the installation process
Figure E-1 Installing PEAR on Windows
Next you need to install PEAR’s database helper package, called MDB2, by typing in the following (see Figure E-2):
pear install MDB2
Figure E-2 Installing the PEAR MDB2 package
474 | Appendix E: Using PEAR and PHPUnit
Trang 5To finish your installation, install the MDB2 add-on driver that understands how to interact with MySQL To do this, type in the following (see Figure E-3):
pear install -f MDB2_Driver_mysql
Figure E-3 Installing the PEAR MySQL MDB2 driver
If you receive an error message at any point from a pop-up window that says “Invalid configuration directive” while installing PEAR or MDB2, you should be able to safely ignore it by clicking the OK button
Finally, as there appears to be a problem with file and path locations in EasyPHP 3.0, you need to type the following command to copy the PEAR files to a location where they can be found by PHP:
xcopy /E pear\*.* includes
Mac OS
Most Macs come supplied with a version of PEAR, but often it’s out of date The safest bet is to ensure that you have the latest version by visiting http://pear.php.net/go-pear
in your browser and then using Save As to save the file that loads into your browser as
go-pear.php in your MAMP htdocs folder Once saved, ensure that you have MAMP
running and enter the following into your browser’s address bar:
http://localhost/go-pear.php
Now all you have to do is click on the Next >> button to see the main installation screen (see Figure E-4) Ensure that the MDB2 checkbox is checked and then edit the Instal-lation prefix field to read:
/Applications/MAMP
Installation | 475
Trang 6Finally, scroll to the bottom of the page and click the Install button You can now sit back and watch the installation as it progresses
Once the installation completes, you will need to add the PEAR installation path to
your include path To do this, open up the file /Applications/MAMP/conf/php5/
php.ini in a text or program editor and locate the line that reads:
include_path = ".:/Applications/MAMP/bin/PHP5/lip/php"
Now change the string after include_path = to read:
".:/Applications/MAMP/bin/PHP5/lip/php:/Applications/MAMP/PEAR"
Once you have done this, pull up the MAMP control panel and stop and restart the servers If prompted, you may also have to enter your Mac password, too
The last part of the installation involves downloading and adding the MySQL driver to PEAR To do this, call up the Terminal and type the following The output on the Terminal will look like Figure E-5
/Applications/MAMP/bin/pear install MDB2_Driver_mysql
Figure E-4 Installing Pear and MDB2
476 | Appendix E: Using PEAR and PHPUnit
Trang 7If you installed the XAMPP package in Chapter 2, you already have PEAR installed However, you will need to install the MDB2 database access package and the MySQL driver for it To do this, you should need to issue only the following two commands: pear install MDB2
pear install MDB2_Driver_mysql
Creating a Connect Instance
With all of PEAR, the MDB2 package, and the MySQL driver installed, you can start
to take advantage of these new additions But to do so, you need to understand what MDB2 is providing you with: a layer of abstraction
In other words, MDB2 knows everything about accessing any major brand of database program you may have installed You simply use a common set of commands and tell MDB2 which database to access This means you can migrate to another SQL database such as PostgreSQL and will only have to install the new MDB2 driver and change a single line of code in your PHP file to be up and running again
You connect to a MySQL database using MDB2 with code such as the following, where
$db_username and the other $db_ variables have already been read in from the
login.php file:
Figure E-5 Installing the PEAR MySQL MDB2 driver
Creating a Connect Instance | 477
Trang 8require_once 'MDB2.php';
$dsn = "$db_username:$db_password@$db_hostname/$db_database";
$mdb2 = MDB2::connect("mysql://$dsn");
The require_once line loads MDB2 In the next line, the variable $dsn stands for data
source name and is an identifier for the database It comprises username:password@hostname/database The variable $mdb2 is an object returned by calling the connect method within the MDB2 class Recall that as mentioned in Chap-ter 5, the double colon (::) token indicates a class to be used on the left and a method
to call from that class to the right
The full string passed to the connect method is as follows:
mysql://username:password@hostname/database
The mysql:// at the head of the string identifies the MDB2 driver to use and hence the
type of database to access If, for example, you were using a PostgreSQL database you
would replace the head with pgsql:// The possible database types supported (as long
as you install the drivers) are fbsql, ibase, mssql, mysql, mysqli, oci8, pgsql, querysim, and sqlite.
To check whether the program successfully connected to the database, you can issue
a call to the PEAR isError method, like this:
if (PEAR::isError($mdb2))
die("Unable to connect to MySQL: " $mdb2->getMessage());
Here the $mdb2 object is passed to the isError method, which returns TRUE if there is an error In that case the die function is called, and an error message is issued before calling the getMessage method from within the $mdb2 object to output the last message, de-scribing the error encountered
Querying
Once you have an MDB2 object in $mdb2, you can use it to query the database Instead
of calling the mysql_query function, call the query method of the $mdb2 object as follows (assuming that the variable $query has already been assigned a query string):
$result = $mdb2->query($query);
Fetching a Row
The variable $result, returned by the query method, is another object To fetch a row from the database, just call the object’s fetchRow method like this:
$row = $result->fetchRow();
You can also determine the number of rows in $result using the numRows method like this:
$rows = $result->numRows();
478 | Appendix E: Using PEAR and PHPUnit
Trang 9Closing a Connection
To close an MDB2 database connection, call the disconnect method of the $mdb2 object:
$mdb2->disconnect();
Hopefully you now have the hang of this new object-oriented approach to accessing
MySQL So let’s look at how the sqltest.php program in Example 10-8 can be rewritten using PEAR’s MDB2 package (see Example E-1, sqltest_mdb2.php).
Example E-1 Inserting and deleting using MDB2: sqltest_mdb2.php
<?php // sqltest_mdb2.php
require_once 'login.php';
require_once 'MDB2.php';
$dsn = "mysql://$db_username:$db_password@$db_hostname/$db_database";
$options = array('debug' => 2);
$mdb2 = MDB2::connect($dsn,$options);
if (PEAR::isError($mdb2))
die("Unable to connect to MySQL: " $mdb2->getMessage());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category = get_post('category');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
$query = "DELETE FROM classics WHERE isbn='$isbn'";
if (!$mdb2->query($query))
echo "DELETE failed: $query<br />"
$mdb2->getMessage() "<br /><br />";
}
else
{
$query = "INSERT INTO classics VALUES"
"('$author', '$title', '$category', '$year', '$isbn')";
if (!$mdb2->query($query))
echo "INSERT failed: $query<br />"
$mdb2->getMessage() "<br /><br />";
}
Rewriting Example 10-8 to Use PEAR | 479
Trang 10echo <<<_END
<form action="sqltest_mdb2.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title"/ >
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = $mdb2->query($query);
if (!$result) die ("Database access failed: " $mdb2->getMessage());
$rows = $result->numRows();
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = $result->fetchRow();
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest_mdb2.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
$mdb2->disconnect();
function get_post($var)
{
return mysql_real_escape_string(@$_POST[$var]);
}
?>
Looking through this code, you should see that very little has been changed from the nonobject-oriented version of the program, other than replacing the database accessing functions with calls to methods contained within the $mdb2 object, and objects returned from them The differences have been highlighted in bold
I recommend that you try modifying sqltest.php for yourself to use MDB2, as in the example, and then save it as sqltest_mdb2.php to test it.
480 | Appendix E: Using PEAR and PHPUnit