SlideShare uma empresa Scribd logo
1 de 7
#23
                                                                                                                                                                  tech facts at your fingertips
 Get More Refcardz! Visit refcardz.com


                                         CONTENTS INCLUDE:




                                                                                                                                                                                   PHP
                                         n	
                                              Configuration
                                         n	
                                              Popular PEAR Packages
                                         n	
                                              Object-Oriented PHP
                                         n	
                                              Regular Expressions
                                         n	
                                              MySQL Integration
                                         n	
                                              Hot Tips and more...                                                                                                By W. Jason Gilmore

                                                ABOUT THIS REFCARD                                                            POPULAR PEAR PACKAGES

                                               PHP is the world's most popular server-side Web scripting                     The PHP Extension Application Repository (PEAR) is the de facto
                                               language, sporting a syntax simple enough to attract novice                   service for distributing reusable PHP components. Over 500
                                               programmers yet powerful enough to run some of the world's                    packages are available for download from http://pear.php.net/,
                                               most popular websites, among them Yahoo!, Facebook,                           including these popular solutions:
                                               GameSpy, and Vimeo.
                                                                                                                             PEAR Packages      Description
                                               This reference card was created to help you quickly navigate                  Auth               Facilitates authentication against IMAP, LDAP, plaintext files,
                                               some of PHP's most commonplace features, including object-                                       most modern databases, RADIUS, and other authentication
                                               oriented programming, array and string manipulation, regular                                     solutions.
                                               expressions, and MySQL integration.                                           Config             Aids in the management of application configuration data
                                                                                                                             HTML_QuickForm2    Streamlines the creation, processing, and validation of HTML
                                                                                                                                                forms.
                                                CONFIGURATION                                                                HTML_Table         Simplifies the generation of dynamic HTML tables
                                                                                                                             HTTP_Upload        Assists in the management of files uploaded through an
                                               PHP's behavior can be configured at a variety of levels:                                         HTML form.
                                                                                                                             Mail               Facilitates transmission of e-mail through a website by
                                               Global Configuration                                                                             supporting multiple mailer backends (including PHP's native
                                               The php.ini file is PHP's configuration file, containing more                                    mail() function, Sendmail, and SMTP)

                                               than 200 directives capable of tweaking nearly every aspect of                MDB2               A database abstraction layer supporting numerous
                                                                                                                                                databases, including MySQL, PostgreSQL, Oracle, and MS
                                               the language's behavior. This file is parsed every time PHP is                                   SQL.
                                               invoked, which for the server module version occurs only when                 Net_UserAgent_     Provides information regarding the user's browser and
 www.dzone.com




                                               the web server starts, and every time for the CGI version.                    Detect             operating system.
                                                                                                                             PHPDocumentor      Automates the code documentation creation and
                                               Host- and Directory-specific Configuration                                                       management process
                                               If you lack access to the php.ini file, you may be able to change             PHPUnit            Aids in the creation, execution and analysis of application
                                               desired directives within Apache's httpd.conf or .htaccess files.                                tests
                                               For instance, to force the display of all PHP errors for solely your          XML_RPC            Supports creation of PHP-driven XML-RPC clients and
                                               development domain (for instance http://dev.wjgilmore.com),                                      servers.

                                               add the following to a .htaccess file:
                                               php_flag display_errors on                                                     POPULAR FRAMEWORKS

                                                            Each directive is assigned one of three permis-                 Web frameworks help the programmer to embrace best practices,
                                                    Hot     sion levels (PHP_INI_ALL, PHP_INI_PER_DIR, PHP_                 simultaneously decreasing errors and eliminating redundant code.
                                                    Tip     INI_SYSTEM) which determines where it can be                    If you haven't yet settled upon a framework, consider checking out
                                                            set. Be sure to consult the PHP documentation                   one or several of the following popular solutions:
                                                 before tweaking settings outside of the php.ini file. See
                                                 http://www.php.net/ini for a complete list of directives.                                                 Get More Refcardz
                                                                                                                                                                       (They’re free!)
                                               Script-specific Configuration
                                               Occasionally you'll want to tweak directives on a per-script basis.                                            n 	Authoritative content
                                               For instance to change PHP's maximum allowable execution                                                       n 	Designed for developers
                                               time for a script tasked with uploading large files, you could call
                                                                                                                                                              n 	Written by top experts
                                               the ini_set() function from within your PHP script like so:
                                                                                                                                                              n 	Latest tools & technologies
                                               ini_set('max_execution_time', 60);
                                                                                                                                                              n	 Hot tips & examples
                                               Changing the PHP File Extension
                                                                                                                                                              n 	Bonus content online
                                               PHP's default file extension is .php, however you can change it
                                               to whatever you please by adding the desired extension to the                                                  n 	New issue every 1-2 weeks

                                               AddType directive within Apache's httpd.conf file. For instance to
                                               configure Apache to recognize .dzone as a supported PHP file                                   Subscribe Now for FREE!
PHP




                                               extension:                                                                                          Refcardz.com
                                               AddType application/x-httpd-php          .php    .dzone


                                                                                                          DZone, Inc.   |   www.dzone.com
2
                                                                                                                                                                      PHP
     tech facts at your fingertips




Popular Frameworks, continued                                                                    Object-Oriented PHP, continued
Framework                        Source                                                          Class Constants
CakePHP                          http://www.cakephp.org/                                         Class constants are defined with the const keyword, and can
CodeIgniter                      http://www.codeigniter.com/                                     be referenced through the scope resolution operator (::). For
eZ Components                    http://ez.no/ezcomponents                                       instance, to define a constant identifying the RadioStation class'
Prado                            http://www.pradosoft.com/                                       minimum supported PHP version:
symfony                          http://www.symfony-project.org/
Zend Framework                   http://framework.zend.com/                                      const MIN_PHP_VER = '5.3';

                                                                                                 You can then reference it outside the class like so:
    OBJECT-ORIENTED PHP                                                                          echo RadioStation::MIN_PHP_VER;

                                                                                                 Extending Classes
Creating a Class
                                                                                                 Class hierarchies can be created using the extends keyword. For
A class defines the behavior and characteristics of an entity you'd
                                                                                                 instance, an application tasked with cataloging all major media
like to represent in an application. A sample class follows:
                                                                                                 outlets might first define a MediaOutlet class which defines
class RadioStation {
	 private $_id;                                                                                  some broad characteristics, and then child classes such as
	 private $_name;                                                                                RadioStation and TVStation would inherit from it:
	 private $_frequency;
                                                                                                 class MediaOutlet {
	 private $_band;
                                                                                                 	 protected $owner;
	 private $_audioStream;
                                                                                                 	 protected $residentCountry;
	 public function setBand($band) {
		 $this->_band = $band;                                                                         	 public function setOwner($owner) {
	 }                                                                                              		 ...
                                                                                                 	 }
	   public function getBand() {                                                                  }
	   return $this->_band;                                                                         class RadioStation extends MediaOutlet {
	   }                                                                                            	 ...
	   ...                                                                                          }
}                                                                                                If you wanted to prevent child classes (in this case,
Object Instantiation                                                                             RadioStation) from overriding a parent method, prefix it with
                                                                                                 the final keyword. For instance:
To create an instance of a class (known as an object), you call the
class name like you would a function, preceding it with the new                                  final public function setOwner($owner) {
keyword:                                                                                         	 ...
                                                                                                 }
$wtvn = new RadioStation();
                                                                                                 Class Abstraction
Class Constructors
                                                                                                 The aforementioned MediaOutlet class would be more
Constructors are useful for performing initialization tasks at
                                                                                                 accurately defined as an abstract class, because it would never
class instantiation time, thereby saving you the hassle of calling
                                                                                                 be explicitly instantiated (instead, one would instantiate derived
additional class methods. Constructors are declared using the
                                                                                                 classes such as RadioStation, TVStation, Newspaper, etc.).
__construct() method, like so:
                                                                                                 Abstract classes are declared using the abstract keyword:
function __construct($id="") {
	 If specific station ID is requested, retrieve it
   //                                                                                            abstract class MediaOutlet {
   from the database                                                                             	 ...
	 if (isset($id))                                                                                }
					 $this-find($id);
}                                                                                                You can choose to override any methods found within an
                                                                                                 abstract class, which would then be inherited by its child classes,
Class Destructors                                                                                or alternatively you can declare them as abstract, requiring these
Custom class destructors can perform tasks when the object is                                    methods be defined by any child.
destroyed. You can create a destructor using the __destruct()
method:                                                                                          Creating Interfaces
function __destruct() {                                                                          An interface helps developers rigorously enforce application
	 printf(The radio station %s has been destroyed!,                                            specifications, and is similar to an abstract class, but contains
   $this-name);
}
                                                                                                 solely the required method signatures. Any class implementing
                                                                                                 the interface must also implement all defined interface methods.
Attribute and Method Visibility                                                                  Interfaces are defined using the interface keyword and their
PHP supports three levels of attribute and method visibility:                                    names are typically prefixed with a capital I:
Attribute and                Description                                                         interface IRadioStation {
Method Visibility                                                                                	 public function setBand($band);
Public                       Public attributes and methods can be accessed anywhere              	 public function getBand();
                                                                                                 }
Private                      Private attributes and methods are only accessible within
                             the class that defines them                                         class RadioStation implements IRadioStation {
Protected                    Protected attributes and methods are available to the class         	 ...
                             and its subclasses.                                                 }


                                                                              DZone, Inc.   |   www.dzone.com
3
                                                                                                                                                                         PHP
   tech facts at your fingertips




                                                                              Multidimensional Arrays, continued
 WORKING WITH ARRAYS
                                                                              Referencing an element isn't unlike the methods used for
The array is one of programming's most powerful data structures,              indexed and associative arrays; it's just a tad more verbose:
capable of managing a seemingly endless variety of data.                      $channel = $stations[FM][WTVN];

Creating an Array                                                             Determining Array Size
The following two examples all create an array named $stations                The number of elements found in an array can be determined
consisting of three elements:                                                 using the count() function:
                                                                              // Outputs 3 stations are being tracked
 $stations = array (
                                                                              printf(%d stations are being tracked,
   WTVN,
   WBNS,                                                                    count($stations));
   WYTS);
                                                                              Sorting Arrays
 $stations = array();
 $count = array_push($stations, WTVN, WBNS, WYTS);
                                                                              PHP offers a powerful assortment of functions (more than 70)
                                                                              capable of sorting arrays in a variety of ways. Most of these
You can create an array consisting of a character- or numerically-            functions accept an optional parameter which can change the
based range using the range() function:                                       sorting behavior. Four values are supported, including SORT_
// $teenListenerDemographic =                                                 REGULAR for comparing elements without implicit typecasting,
// array(13,14,15,16,17,18,19)                                                SORT_NUMERIC for comparing elements numerically, SORT_STRING
$teenListenerDemographic = range(13,19);                                      for comparing elements as strings, and SORT_LOCALE_STRING, for
                                                                              sorting elements according to the defined locale.
Retrieving Array Contents
                                                                               Description                              Function
Indexed arrays such as those created so far can be accessed
                                                                               Sort an array while maintaining the      bool asort(array $array [, int $sort_flags])
according to their numerical offset (beginning with a zero-                    key association
based offset). For instance to retrieve the second value in the                Reverse sort an associative array        bool arsort(array $array [, int $sort_flags])
$stations array:                                                               while maintaining key association

$callSignal = $stations[1];                                                    Sort an associative array by key,        bool ksort(array $array [, int $sort_flags])
                                                                               maintaining index association
Perhaps the most flexible way to enumerate array contents is                   Reverse sort an associative array by     bool krsort(array $array [, int $sort_flags])
through the foreach statement:                                                 key, maintaining index association

foreach($stations AS $station)                                                 Sort an array case-insensitively in an   bool natcasesort($array array)
                                                                               order logically presumed by humans
	 printf(%sbr /, $station);
                                                                               Sort an array in an order logically      bool natsort(array $array)
Associative Arrays                                                             presumed by humans
                                                                               Sort an array in reverse order           bool rsort(array $array [, int $sort_flags])
Associative arrays give developers the opportunity to assign
meaningful context to both the array value and its corresponding               Sort an array according to the           bool usort(array $array, callback
                                                                               specifications of a user-defined         $comparison_function)
key:                                                                           function
$stations      = array(                                                        Sort an array according to the           bool uasort(array $array, callback
	 WTVN       = 610,                                                       specifications of a user-defined         $comparison_function)
	 WBNS       = 1460,                                                      function, maintaining index
	 WYTS       = 1230                                                       association

);                                                                             Key sort an array according to the       bool uksort(array $array, callback
                                                                               specifications of a user-defined         $comparison_function)
You can then obtain a value (in this case the station/band) by                 function
referencing its call signal:
                                                                              Consult the PHP manual for a complete listing: http://www.php.
// $channel = 610                                                           net/array.
$channel = $stations[WTVN];

The foreach statement proves equally useful for navigating                      STRING PARSING
associative arrays:
foreach($stations AS $key = value)                                           PHP supports over 100 functions identified as specific to string
	 printf(%s = %sbr /, $key, $value);
                                                                              parsing and manipulation. Following are the most commonly
Multidimensional Arrays                                                       used tasks.
Multidimensional arrays are useful for representing more                       Description              Function
complex data structures:                                                       Converting an array      $stations = array(WTVN,WBNS,WYTS);
                                                                               to a string              $stations = implode(,, $stations)
$stations = array(                                                                                      // $stations = WTVN,WBNS,WYTS
	 AM =                                                                      Converting a string      $stations = WTVN,WBNS,WYTS;
	 array(WTVN = 610,                                                       to an array              $stations = explode(,, $stations);
                                                                                                        // $stations[0]=WTVN, $stations[1]=WBNS,
		 WBNS = 1460,                                                                                    $stations[2]=WYTS
		 WYTS = 1230),
                                                                               Counting words in        $sentence = Columbus is home to numerous
	 FM =                                                                                               radio stations;
                                                                               a string
	 array(WLVQ = 96.3,                                                                               $words = str_word_count($sentence);
		 WNCI = 97.9)                                                                                    // $words = 7
                                                                                                        See also: count_chars()
);


                                                           DZone, Inc.   |   www.dzone.com
4
                                                                                                                                                                                                  PHP
       tech facts at your fingertips




String Parsing, continued                                                                              Metacharacters
                                                                                                       A                      Match only beginning of string
Description                     Function
                                                                                                       b                      Match a word boundary
Converting                      $callsign = strtoupper(wtvn);
a string to                                                                                            B                      Match anything but word boundary
                                // $callsign = WTVN
uppercase
                                See also: lcwords(),        strtolower(), ucfirst(),
                                                                                                       d                      Match a digit character
                                ucwords()                                                              D                      Match a non-digit character
Strip HTML and PHP              $input = You won the a href=http://www.                             s                      Match a whitespace character
tags from a string              example.comlottery!/a.
                                $clean = strip_tags($input);                                           S                      Match a non-whitespace character
                                // $clean = You won the lottery!
                                                                                                       []                      Enclose a character class
                                See also: htmlentities(), htmlspecialchars()
                                                                                                       ()                      Enclose a character grouping or define backreference
Replace all                     $phrase = Big rockers listen to rock radio;
                                                                                                       $                       Match end of line
occurrences of a                $phrase = str_replace(rock, talk, $phrase);
substring                       // $phrase = Big talkers listen to talk radio                        ^                       Match beginning of line
                                See also: substr_replace(), strireplace(),                             .                       Match any character except for newline
                                strtr()
                                                                                                                              Quote the next metacharacter
Return part of a string $description = WFAN: Sports Radio 66;
as specified by an      $callsign = substr($description, 0, 4);                                        w                      Match any string containing underscore and alphanumeric
offset                  See also: strrchr()                                                                                    characters
                                                                                                       W                      Match a string containing anything but underscore and
Compare two strings             if (strcasecmp(WTVN, wtvn) == 0)                                                           alphanumericl characters
case-insensitively              	 echo The strings are equal in a case-
                                insensitive context.
                                                                                                       POSIX Regular Expression Functions
                                See also: strncasecmp()
                                                                                                       PHP supports seven functions as defined by the POSIX 1003.2
Convert newline                 $stations = WTVN: 610nWLW: 700nWYTS: 1230;                         specification, including these commonly used solutions:
characters to the               $html = nl2br($stations);
HTML br / tag                 // $html = WTVN: 610br /WLW: 700br /WYTS:                          int ereg(str $pattern, str $string   Search $string for a $pattern. You can optionally
                                1230
                                                                                                        [, array $regs])                    include the $regs parameter, which will cause
                                See also: htmlentities(), htmlspecialchars()                                                                 an array of the same name to be returned
                                                                                                                                             containing each match. See eregi() for case-
                                                                                                                                             insensitive counterpart.
                                                                                                        string ereg_replace(str              Replace any patterns found in string with
    REGULAR EXPRESSIONS                                                                                 $pattern, str $replacement, str      replacement. See eregi_replace() for case-
                                                                                                        $string)                             insensitive counterpart.
                                                                                                        array split(str $pattern, str        Split $string into an array, dividing it according
PHP's regular expression features borrow heavily from both the                                          $string [, int $limit])              to $pattern. See spliti() for case-insensitive
Perl and POSIX formats, and in fact are formally identified as                                                                               counterpart.
such.
                                                                                                       POSIX Regular Expression Syntax
Perl-compatible (PCRE) Regular Expression Functions
                                                                                                       [0-9]                  Any decimal digit from 0 - 9
PHP supports eight PCRE-specific functions, including these
                                                                                                       [a-z]                  Any character from lowercase a through lowercase z
commonly used solutions:
                                                                                                       [A-Z]                  Any character from uppercase A through uppercase Z
    Function                           Description                                                     [A-Za-z]               Any character from upper case A through lowercase z

    array preg_grep(str                Searches $subject for $pattern, returning an array of           p+                     Any string containing at least one p
    $pattern, array $subject           matches. The optional $flags parameter can be set to            p*                     Any string containing zero or more p's
    [, int $flags])                    PREG_GREP_INVERT, causing an array consisting of
                                       unmatched elements to be returned.                              p?                     Any string containing zero or one p
                                                                                                       p{N}                   Any string containing sequence of two p's
    int preg_match(str                 Determines whether $pattern exists in $subject. If
                                                                                                       p{N,M}                 Any string containing sequence of between N and M p's
    $pattern, str $subject [,          $matches is defined, a similarly named variable will
    array $matches [, int             be returned containing the matches. If $flags is set to         p{2,}                  Any string containing sequence of at least two p's
    $flags [, int $offset]]])          PREG_OFFSET_CAPTURE, the string offset value will
                                                                                                       p$                     Any string with p at the end of it
                                       also be returned for each match. See preg_match_all()
                                       for a variation of this function.                               ^p                     Any string with p at the beginning of it
                                                                                                       [^a-zA-Z]              Any string not containing characters a-z through A-Z
    mixed preg_                        Searches $subject for $pattern, replacing any
    replace(mixed $pattern,            instances with $replacement. See preg_replace_                  p.p                    Any string containing p followed by any character, followed by
    mixed $replacement,                callback() for a variation of this function.                                           another p
    mixed $subject [, int
    $limit [, int $count]])                                                                           Regular Expression Examples
                                                                                                       Validating a Phone Number
Common PCRE Pattern Modifiers                                                                          Presumes the required format is XXX-XXX-XXXX.
Modifier                    Description                                                                // PCRE
g                           Perform a global search
                                                                                                       if (preg_match('/^[2-9]{1}d{2}-d{3}-d{4}$/', '614-
                                                                                                       599-2599'))
i                           Perform a case-insensitive search
                                                                                                       	 echo Valid number!;
m                           Treat the string as multiple lines (
                                                                                                       // POSIX
s                           Ignore newline characters
                                                                                                       if (ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', '614-
x                           Ignore white space and comments
                                                                                                       999-2599'))
u                           Stop at the first match (ungreedy search)
                                                                                                       	 echo Valid number!;


                                                                                    DZone, Inc.   |   www.dzone.com
5
                                                                                                                                                                                            PHP
     tech facts at your fingertips




Validating a Username                                                                       Telling Time with PHP, continued
Presumes username is between 6 and 10 alphabetical and
numerical characters.                                                                       Month Parameters
//   PCRE                                                                                    F               Full text representation of month

if   (preg_match('/^[a-z0-9]{6,10}$/i', '800gilmore'))                                       m               Numeric representation of month
	    echo Valid username!;                                                                 M               Three letter textual representation of month
//   POSIX                                                                                   n               Numeric representation of month, without leading zeros
if   (eregi('^[a-z0-9]{6,10}$', '800gilmore'))                                               t               Number of days in given month
	    echo Valid username!;
                                                                                            Year Parameters
Turn URLs into hyperlinks                                                                    L               Whether date is a leap year
// PCRE
                                                                                             o               ISO-8601 year number
$text = Go to http://www.wjgilmore.com.;
                                                                                             Y               Full numeric representation of year
$html = preg_replace('/s(w+://)(S+.?)(w+)/',
                                                                                             y               Two digit representation of year
			 ' a href=123123/a', $text);
// POSIX
$text = Go to http://www.wjgilmore.com. ;
                                                                                            Date Function Examples
$html= ereg_replace('[a-zA-Z]+://(([.]?[a-zA-                                                July 29, 2008                                  print date('F j, Y');
Z0-9_/-])*)', 'a href=00/a', $string);                                             7/29/08                                        print date('m/j/y');
// $html = Go to a href= http://www.wjgilmore.
                                                                                             Today is Tuesday, July 29 10:45:21am           printf(Today is %s, date('l, F j h:i:sa'));
comhttp://www.wjgilmore.com.
                                                                                             There are 31 days in July.                     printf(There are %d days in %s.,
                                                                                                                                            date('t'), date('F'));

    TELLING TIME WITH PHP
                                                                                            Setting the Timezone
The Date Function                                                                           You can set the timezone for all scripts by setting the date.
                                                                                            timezone configuration directive within the php.ini file, or on
The date() f unction is perhaps one of PHP's most commonly
                                                                                            a per-script basis using the date_default_timezone_set()
used functions, capable of retrieving nearly every temporal
                                                                                            function.
attribute of a specific timestamp.
string date(string $format [, $int $timestamp])                                             Other Useful Functions
a             Lowercase Ante meridiem and Post meridiem                                     Function                                        Description
A             Uppercase Ante meridiem and Post meridiem                                      int mktime([int $hour [, int $min [, int       Returns the Unix timestamp for a given
                                                                                             $sec [, int $month [, int $day [, int $year    date
B             Swatch Internet Time
                                                                                             [, int $is_dst]]]]]]])
c             ISO 8601 date
                                                                                             int time()                                     Returns current timestamp
e             Timezone identifier
                                                                                             string setlocale(int $category, string         Sets the script locale
g             12-hour hour format without leading zeros                                      $locale)
G             24-hour hour format with leading zeros
                                                                                             int strtotime(string $time [, int $now])       Converts English textual date/time
h             12-hour hour format with leading zeros                                                                                        description into a Unix timestamp
H             24-hour hour format with leading zeros                                         bool checkdate(int $month, int $day,           Validates the date composed by the
i             Minutes with leading zeros                                                     int $year)                                     $month, $day, and $year arguments.

I             Specifies whether date is in daylight savings time                             array getdate([int $timestamp])                Retrieves a timestamp as an associative
                                                                                                                                            array. Associative keys include seconds,
O             Difference to Greenwich time (GMT) in hours                                                                                   minutes, hours, mday (day of the
P             Difference to Greenwhich time (GMT) with colon between hours and                                                              month), wday (day of week), mon
              minutes                                                                                                                       (month), year, yday (day of the year),
                                                                                                                                            weekday, month, and 0 (seconds since
r             RFC 2822 date
                                                                                                                                            UNIX Epoch)
s             Seconds, with leading zeros
T             Timezone abbreviation                                                         PHP 5.1.0 introduced an object-oriented DateTime class. See
u             Milliseconds                                                                  http://www.php.net/DateTime for more information.
U             Seconds since Unix Epoch
                                                                                            Date-related Examples
z             Timezone offset in seconds
                                                                                             Output December 25          $date = date('l', mktime(0,0,0,12,25,2008));
Day Parameters                                                                               falls on a Thursday         printf(December 25 falls on a %s, $date);

d                Day of month, two digits with leading zeros                                 Output Next month is printf(Next month is %s, date('F', strtotime('+1
                                                                                             August.              month')));
D                Three letter textual representation of day
                                                                                             Output Last Friday          $date = date('F d, Y', strtotime('Last Friday'));
j                Day of month without leading zeros
                                                                                             fell on July 25, 2008       printf(Last Friday fell on %s, $date);
l                Textual representation of day
                                                                                             Output Oggi è               setlocale(LC_ALL, it_IT);
N                ISO-8601 numeric representation
                                                                                             martedì                     printf(Oggi egrave; %s, strftime(%A));
S                Two character English ordinal suffix for day of month
                                                                                             Retrieve a page's last-      echo date('l, F j h:i:sa', filemtime($_SERVER[SCRIPT_
w                Numeric representation of day of week                                       modified date                NAME]));
z                Numerical offset of day of year
                                                                                             Calculate the                $date1 = strtotime(2008-08-14);
                                                                                             difference between           $date2 = strtotime(2008-07-11);
Week Parameters                                                                              two dates
                                                                                                                          $diff = $date2 - $date1;
W ISO-8601           week number of year                                                                                  printf(Difference in days: %s, $diff / 60 / 60 / 24);



                                                                         DZone, Inc.   |   www.dzone.com
6
                                                                                                                                              PHP
   tech facts at your fingertips




                                                                            Retrieving data as an indexed array:
 MYSQL INTEGRATION                                                          while ($row = $result-fetch_row() {
                                                                            	 printf(%S, $row[0]);
Although PHP supports several popular databases, MySQL                      }
remains by far the most common database solution. PHP's                     Retrieving data as an object:
MySQL support has evolved considerably in recent years, with                while ($row = $result-fetch_object() {
the MySQLi (MySQL Improved) extension being the current                     	 printf(%S, $row-callsign);
recommended solution. Here are the most commonly used                       }
methods.
                                                                            Determining the Number of Rows Affected and Retrieved
                                                                            To determine the number of affected rows after sending an
               The PHP 5.3 release includes a new MySQL
     Hot                                                                    INSERT, UPDATE, or DELETE query, use the affected_rows
               driver known as mysqlnd (MySQL Native Driver).
     Tip       This driver eliminates the need for a previously
                                                                            property.

               required special licensing exception (FLOSS), and            Example:
  eliminates the need to have MySQL installed on the same ma-               $result = $mysqli-query(UPDATE stations SET station =
                                                                            '610' WHERE callsign = 'WTVN');
  chine as PHP. It has already been integrated with the mysql               printf(Rows affected: %d, $result-rows_affected);
  and mysqli extensions, with PDO support in the works.
                                                                            To determine how many rows were returned when using a
                                                                            SELECT query, use the num_rows property:
Connecting to MySQL                                                         $result = $mysqli-query(SELECT * FROM stations WHERE
                                                                            state ='Ohio');
The mysqli extension provides a number of ways to connect to
MySQL, but the easiest involves just passing the connection data            printf(Rows affected: %d, $result-num_rows);
along when instantiating the mysqli class:
                                                                            Working with Prepared Statements
mysqli new mysqli([string host [, string user [, string
pswd                                                                        Prepared statements both optimize query performance and
	 [string dbname [int port [string socket]]]]]]);                           decrease the possibility of SQL injection attacks by separating
                                                                            the query data from the logic, first passing the query to MySQL
Here's an example:
                                                                            for preparation, binding variables to the query columns, and
$mysqli = new mysqli(localhost, webuser, secret,
corporate);                                                               finally passing the data to MySQL for query execution.
                                                                            To prepare a query, create the query, and then initialize a
Handling Connection Errors
                                                                            statement object using the stmt_init() method:
In case of connection error you can retrieve both the error                 $query = INSERT INTO stations VALUES(?, ?);
number and error string using the errno() and error()
                                                                            $stmt = $mysqli-stmt_init();
methods. Example:
if ($mysqli-errno) {                                                       Next the query is prepared by passing it to MySQL using the
	 printf(Unable to connect: %s, $mysqli-error);                          prepare() method:
	 exit();                                                                   $stmt-prepare($query);
}
                                                                            Next, bind the parameters using the bind_param() method:
Sending a Query to the Database                                             $stmt-bind_param('ss', WTVN, 610);
Once the connection has been established, you can begin                     Finally, execute the prepared statement using the execute()
querying the database. Queries are sent using the query()                   method:
method:                                                                     $stmt-execute();
mixed query(string $query [, int $resultmode])
                                                                            You can also use prepared statements to retrieve results. The
Setting the optional $resultmode parameter to MYSQLI_USE_                   general process used to execute the previous INSERT query is
RESULT will cause query() to return the result as an unbuffered             identical to that required for executing a SELECT query, except
set.                                                                        that the bind_param() method is not required, and you bind
Example:                                                                    results following a call to the execute() method. An example
$result = $mysqli-query(SELECT callsign FROM                              follows:
stations);
                                                                            $query = SELECT callsign, frequency FROM stations
                                                                                     
Sending INSERT, UPDATE, and DELETE queries works                                      ORDER BY callsign;
identically. For instance, sending an UPDATE query works like               $stmt = $mysqli-stmt_init();
this:                                                                       $stmt-prepare($query);
 $result = $mysqli-query(UPDATE stations SET station                      $stmt-execute();
= '610' WHERE callsign = 'WTVN');                                          $stmt-bind_result($callsign, $frequency);
                                                                            while ($stmt-fetch())
Retrieving Data                                                             	 printf(%s: %sbr /, $callsign, $frequency);
Data can be parsed from the result set using a number of data
structures, including via associative and indexed arrays, and               Transactions
objects.                                                                    By default the MySQLi extension will render each query
                                                                            permanent upon successful execution, actually changing the
Retrieving data as an associative array:
while ($row = $result-fetch_array(MYSQLI_ASSOC) {                          database's contents when INSERT, UPDATE, and DELETE queries
	 printf(%S, $row[callsign]);                                           are processed. However the success of some tasks depend upon
}                                                                           the successful execution of several queries, and until all have


                                                         DZone, Inc.   |   www.dzone.com
7
                                                                                                                                                                                                                              PHP
               tech facts at your fingertips




        Transactions, continued
                                                                                                                                     USEFUL ONLINE RESOURCES
        successfully executed, no changes to the database should actually
        occur. ATM transactions and online credit card processing are
        common examples requiring several queries. Using transactions,                                                              Resource                                                Source
        you can change the MySQLi extension's behavior, committing a                                                                PHP Zone                                                http://php.dzone.com
        series of queries as you see fit.
                                                                                                                                    The PHP Website                                         http://www.php.net
        To begin a transaction, start by disabling the autocommit feature:
                                                                                                                                    Zend Developer Zone                                     http://devzone.zend.com/
        $mysqli-autocommit(FALSE);
                                                                                                                                    PlanetPHP                                               http://www.planet-php.net/
        Execute the various queries as you see fit, and if everything
        proceeds as you expect, execute the commit() method:                                                                        PHPDeveloper.org                                        http://phpdeveloper.org/
        $mysqli-commit();
                                                                                                                                    Developer.com                                           http://www.developer.com/
        Otherwise, if a problem occurs, execute the rollback() method:
                                                                                                                                    ONLamp PHP Devcenter                                    http://www.onlamp.com/php/
        $mysqli-rollback();




   ABOUT THE AUTHOR                                                                                                                                                 RECOMMENDED BOOK

                               W. Jason Gilmore                                                                                                                                                   Beginning PHP and MySQL is
                     Jason Gilmore is founder of W.J. Gilmore, LLC, providing web development,                                                                                                    the definitive book on the PHP
                     consulting, and technical writing services to clientele ranging from publicly                                                                                                language and MySQL database.
                     traded corporations to small startups. Jason is a prolific contributor to a                                                                                                  Readers are treated to compre-
                     number of leading publications such as Developer.com, Linux Magazine,                                                                                                        hensive introductions of both
                     and TechTarget, with almost 100 articles to his credit. He's cofounder of the                                                                                                technologies, and in addition to
                     CodeMash conference (http://www.codemash.org/), a non-profit organiza-                                                                                                       in-depth instruction regarding
   tion charged with organizing the annual namesake event.
                                                                                                                                                                                                  using these two technologies in
   Publications                                                                                                                                                       unison to build dynamic web sites.
   n   Beginning PHP and MySQL
   n   Beginning PHP and PostgreSQL 8 with Robert H. Treat
   n   Beginning PHP and Oracle

   Website                                                                                                                                                                          BUY NOW
   http://www.wjgilmore.com                                                                                                                                                books.dzone.com/books/phpsql


Get More FREE Refcardz. Visit refcardz.com now!
Upcoming Refcardz:                                              Available:
Core Seam                                                       Essential Ruby                                       Core CSS: Part I

Core CSS: Part III                                              Essential MySQL                                      Struts2
                                                                JUnit and EasyMock                                   Core .NET
Hibernate Search
                                                                Getting Started with MyEclipse                       Very First Steps in Flex
                                                                                                                                                                                    FREE
Equinox                                                         Spring Annotations                                   C#

EMF                                                             Core Java                                            Groovy
                                                                Core CSS: Part II                                    NetBeans IDE 6.1 Java Editor
XML
                                                                PHP                                                  RSS and Atom
JSP Expression Language                                         Getting Started with JPA                             GlassFish Application Server
ALM Best Practices                                              JavaServer Faces                                     Silverlight 2                                                                               Design Patterns
                                                                                                                                                                                                            Published June 2008
HTML and XHTML                                                  Visit refcardz.com for a complete listing of available Refcardz.




                                                                                                                             DZone, Inc.
                                                                                                                             1251 NW Maynard
                                                                                                                                                                                              ISBN-13: 978-1-934238-27-1
                                                                                                                             Cary, NC 27513
                                                                                                                                                                                              ISBN-10: 1-934238-27-9
                                                                                                                                                                                                                          50795
                                                                                                                             888.678.0399
 DZone communities deliver over 4 million pages each month to                                                                919.678.0300
 more than 1.7 million software developers, architects and decision
                                                                                                                             Refcardz Feedback Welcome
 makers. DZone offers something for everyone, including news,                                                                refcardz@dzone.com
                                                                                                                                                                                                                                       $7.95




 tutorials, cheatsheets, blogs, feature articles, source code and more.                                                      Sponsorship Opportunities                                     9 781934 238271
 “DZone is a developer’s dream,” says PC Magazine.                                                                           sales@dzone.com
 Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,                          Version 1.0
 photocopying, or otherwise, without prior written permission of the publisher. Reference: Beginning PHP and MySQL, Jason Gilmore, Apress, 2008.

Mais conteúdo relacionado

Semelhante a Rc023 php online

Semelhante a Rc023 php online (20)

Php myadmin
Php myadminPhp myadmin
Php myadmin
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php ppt
Php pptPhp ppt
Php ppt
 
How PHP works
How PHP works How PHP works
How PHP works
 
Training ppt
Training pptTraining ppt
Training ppt
 
PHP
PHPPHP
PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Function of PHP in Website Development
Function of PHP in Website DevelopmentFunction of PHP in Website Development
Function of PHP in Website Development
 
Lamp
LampLamp
Lamp
 
Wp Presentation
Wp PresentationWp Presentation
Wp Presentation
 
6 3 tier architecture php
6 3 tier architecture php6 3 tier architecture php
6 3 tier architecture php
 
Php training in bhubaneswar
Php training in bhubaneswar Php training in bhubaneswar
Php training in bhubaneswar
 
Php training in bhubaneswar
Php training in bhubaneswar Php training in bhubaneswar
Php training in bhubaneswar
 
24307183 php
24307183 php24307183 php
24307183 php
 
Trusted PHP Development Services in the USA
Trusted PHP Development Services in the USATrusted PHP Development Services in the USA
Trusted PHP Development Services in the USA
 
PHP Web Development Language.docx
PHP Web Development Language.docxPHP Web Development Language.docx
PHP Web Development Language.docx
 
CONTENT MANAGEMENT SYSTEM
CONTENT MANAGEMENT SYSTEMCONTENT MANAGEMENT SYSTEM
CONTENT MANAGEMENT SYSTEM
 
Facebook architecture
Facebook architectureFacebook architecture
Facebook architecture
 
Facebook architecture
Facebook architectureFacebook architecture
Facebook architecture
 
Qcon 090408233824-phpapp01
Qcon 090408233824-phpapp01Qcon 090408233824-phpapp01
Qcon 090408233824-phpapp01
 

Rc023 php online

  • 1. #23 tech facts at your fingertips Get More Refcardz! Visit refcardz.com CONTENTS INCLUDE: PHP n Configuration n Popular PEAR Packages n Object-Oriented PHP n Regular Expressions n MySQL Integration n Hot Tips and more... By W. Jason Gilmore ABOUT THIS REFCARD POPULAR PEAR PACKAGES PHP is the world's most popular server-side Web scripting The PHP Extension Application Repository (PEAR) is the de facto language, sporting a syntax simple enough to attract novice service for distributing reusable PHP components. Over 500 programmers yet powerful enough to run some of the world's packages are available for download from http://pear.php.net/, most popular websites, among them Yahoo!, Facebook, including these popular solutions: GameSpy, and Vimeo. PEAR Packages Description This reference card was created to help you quickly navigate Auth Facilitates authentication against IMAP, LDAP, plaintext files, some of PHP's most commonplace features, including object- most modern databases, RADIUS, and other authentication oriented programming, array and string manipulation, regular solutions. expressions, and MySQL integration. Config Aids in the management of application configuration data HTML_QuickForm2 Streamlines the creation, processing, and validation of HTML forms. CONFIGURATION HTML_Table Simplifies the generation of dynamic HTML tables HTTP_Upload Assists in the management of files uploaded through an PHP's behavior can be configured at a variety of levels: HTML form. Mail Facilitates transmission of e-mail through a website by Global Configuration supporting multiple mailer backends (including PHP's native The php.ini file is PHP's configuration file, containing more mail() function, Sendmail, and SMTP) than 200 directives capable of tweaking nearly every aspect of MDB2 A database abstraction layer supporting numerous databases, including MySQL, PostgreSQL, Oracle, and MS the language's behavior. This file is parsed every time PHP is SQL. invoked, which for the server module version occurs only when Net_UserAgent_ Provides information regarding the user's browser and www.dzone.com the web server starts, and every time for the CGI version. Detect operating system. PHPDocumentor Automates the code documentation creation and Host- and Directory-specific Configuration management process If you lack access to the php.ini file, you may be able to change PHPUnit Aids in the creation, execution and analysis of application desired directives within Apache's httpd.conf or .htaccess files. tests For instance, to force the display of all PHP errors for solely your XML_RPC Supports creation of PHP-driven XML-RPC clients and development domain (for instance http://dev.wjgilmore.com), servers. add the following to a .htaccess file: php_flag display_errors on POPULAR FRAMEWORKS Each directive is assigned one of three permis- Web frameworks help the programmer to embrace best practices, Hot sion levels (PHP_INI_ALL, PHP_INI_PER_DIR, PHP_ simultaneously decreasing errors and eliminating redundant code. Tip INI_SYSTEM) which determines where it can be If you haven't yet settled upon a framework, consider checking out set. Be sure to consult the PHP documentation one or several of the following popular solutions: before tweaking settings outside of the php.ini file. See http://www.php.net/ini for a complete list of directives. Get More Refcardz (They’re free!) Script-specific Configuration Occasionally you'll want to tweak directives on a per-script basis. n Authoritative content For instance to change PHP's maximum allowable execution n Designed for developers time for a script tasked with uploading large files, you could call n Written by top experts the ini_set() function from within your PHP script like so: n Latest tools & technologies ini_set('max_execution_time', 60); n Hot tips & examples Changing the PHP File Extension n Bonus content online PHP's default file extension is .php, however you can change it to whatever you please by adding the desired extension to the n New issue every 1-2 weeks AddType directive within Apache's httpd.conf file. For instance to configure Apache to recognize .dzone as a supported PHP file Subscribe Now for FREE! PHP extension: Refcardz.com AddType application/x-httpd-php .php .dzone DZone, Inc. | www.dzone.com
  • 2. 2 PHP tech facts at your fingertips Popular Frameworks, continued Object-Oriented PHP, continued Framework Source Class Constants CakePHP http://www.cakephp.org/ Class constants are defined with the const keyword, and can CodeIgniter http://www.codeigniter.com/ be referenced through the scope resolution operator (::). For eZ Components http://ez.no/ezcomponents instance, to define a constant identifying the RadioStation class' Prado http://www.pradosoft.com/ minimum supported PHP version: symfony http://www.symfony-project.org/ Zend Framework http://framework.zend.com/ const MIN_PHP_VER = '5.3'; You can then reference it outside the class like so: OBJECT-ORIENTED PHP echo RadioStation::MIN_PHP_VER; Extending Classes Creating a Class Class hierarchies can be created using the extends keyword. For A class defines the behavior and characteristics of an entity you'd instance, an application tasked with cataloging all major media like to represent in an application. A sample class follows: outlets might first define a MediaOutlet class which defines class RadioStation { private $_id; some broad characteristics, and then child classes such as private $_name; RadioStation and TVStation would inherit from it: private $_frequency; class MediaOutlet { private $_band; protected $owner; private $_audioStream; protected $residentCountry; public function setBand($band) { $this->_band = $band; public function setOwner($owner) { } ... } public function getBand() { } return $this->_band; class RadioStation extends MediaOutlet { } ... ... } } If you wanted to prevent child classes (in this case, Object Instantiation RadioStation) from overriding a parent method, prefix it with the final keyword. For instance: To create an instance of a class (known as an object), you call the class name like you would a function, preceding it with the new final public function setOwner($owner) { keyword: ... } $wtvn = new RadioStation(); Class Abstraction Class Constructors The aforementioned MediaOutlet class would be more Constructors are useful for performing initialization tasks at accurately defined as an abstract class, because it would never class instantiation time, thereby saving you the hassle of calling be explicitly instantiated (instead, one would instantiate derived additional class methods. Constructors are declared using the classes such as RadioStation, TVStation, Newspaper, etc.). __construct() method, like so: Abstract classes are declared using the abstract keyword: function __construct($id="") { If specific station ID is requested, retrieve it // abstract class MediaOutlet { from the database ... if (isset($id)) } $this-find($id); } You can choose to override any methods found within an abstract class, which would then be inherited by its child classes, Class Destructors or alternatively you can declare them as abstract, requiring these Custom class destructors can perform tasks when the object is methods be defined by any child. destroyed. You can create a destructor using the __destruct() method: Creating Interfaces function __destruct() { An interface helps developers rigorously enforce application printf(The radio station %s has been destroyed!, specifications, and is similar to an abstract class, but contains $this-name); } solely the required method signatures. Any class implementing the interface must also implement all defined interface methods. Attribute and Method Visibility Interfaces are defined using the interface keyword and their PHP supports three levels of attribute and method visibility: names are typically prefixed with a capital I: Attribute and Description interface IRadioStation { Method Visibility public function setBand($band); Public Public attributes and methods can be accessed anywhere public function getBand(); } Private Private attributes and methods are only accessible within the class that defines them class RadioStation implements IRadioStation { Protected Protected attributes and methods are available to the class ... and its subclasses. } DZone, Inc. | www.dzone.com
  • 3. 3 PHP tech facts at your fingertips Multidimensional Arrays, continued WORKING WITH ARRAYS Referencing an element isn't unlike the methods used for The array is one of programming's most powerful data structures, indexed and associative arrays; it's just a tad more verbose: capable of managing a seemingly endless variety of data. $channel = $stations[FM][WTVN]; Creating an Array Determining Array Size The following two examples all create an array named $stations The number of elements found in an array can be determined consisting of three elements: using the count() function: // Outputs 3 stations are being tracked $stations = array ( printf(%d stations are being tracked, WTVN, WBNS, count($stations)); WYTS); Sorting Arrays $stations = array(); $count = array_push($stations, WTVN, WBNS, WYTS); PHP offers a powerful assortment of functions (more than 70) capable of sorting arrays in a variety of ways. Most of these You can create an array consisting of a character- or numerically- functions accept an optional parameter which can change the based range using the range() function: sorting behavior. Four values are supported, including SORT_ // $teenListenerDemographic = REGULAR for comparing elements without implicit typecasting, // array(13,14,15,16,17,18,19) SORT_NUMERIC for comparing elements numerically, SORT_STRING $teenListenerDemographic = range(13,19); for comparing elements as strings, and SORT_LOCALE_STRING, for sorting elements according to the defined locale. Retrieving Array Contents Description Function Indexed arrays such as those created so far can be accessed Sort an array while maintaining the bool asort(array $array [, int $sort_flags]) according to their numerical offset (beginning with a zero- key association based offset). For instance to retrieve the second value in the Reverse sort an associative array bool arsort(array $array [, int $sort_flags]) $stations array: while maintaining key association $callSignal = $stations[1]; Sort an associative array by key, bool ksort(array $array [, int $sort_flags]) maintaining index association Perhaps the most flexible way to enumerate array contents is Reverse sort an associative array by bool krsort(array $array [, int $sort_flags]) through the foreach statement: key, maintaining index association foreach($stations AS $station) Sort an array case-insensitively in an bool natcasesort($array array) order logically presumed by humans printf(%sbr /, $station); Sort an array in an order logically bool natsort(array $array) Associative Arrays presumed by humans Sort an array in reverse order bool rsort(array $array [, int $sort_flags]) Associative arrays give developers the opportunity to assign meaningful context to both the array value and its corresponding Sort an array according to the bool usort(array $array, callback specifications of a user-defined $comparison_function) key: function $stations = array( Sort an array according to the bool uasort(array $array, callback WTVN = 610, specifications of a user-defined $comparison_function) WBNS = 1460, function, maintaining index WYTS = 1230 association ); Key sort an array according to the bool uksort(array $array, callback specifications of a user-defined $comparison_function) You can then obtain a value (in this case the station/band) by function referencing its call signal: Consult the PHP manual for a complete listing: http://www.php. // $channel = 610 net/array. $channel = $stations[WTVN]; The foreach statement proves equally useful for navigating STRING PARSING associative arrays: foreach($stations AS $key = value) PHP supports over 100 functions identified as specific to string printf(%s = %sbr /, $key, $value); parsing and manipulation. Following are the most commonly Multidimensional Arrays used tasks. Multidimensional arrays are useful for representing more Description Function complex data structures: Converting an array $stations = array(WTVN,WBNS,WYTS); to a string $stations = implode(,, $stations) $stations = array( // $stations = WTVN,WBNS,WYTS AM = Converting a string $stations = WTVN,WBNS,WYTS; array(WTVN = 610, to an array $stations = explode(,, $stations); // $stations[0]=WTVN, $stations[1]=WBNS, WBNS = 1460, $stations[2]=WYTS WYTS = 1230), Counting words in $sentence = Columbus is home to numerous FM = radio stations; a string array(WLVQ = 96.3, $words = str_word_count($sentence); WNCI = 97.9) // $words = 7 See also: count_chars() ); DZone, Inc. | www.dzone.com
  • 4. 4 PHP tech facts at your fingertips String Parsing, continued Metacharacters A Match only beginning of string Description Function b Match a word boundary Converting $callsign = strtoupper(wtvn); a string to B Match anything but word boundary // $callsign = WTVN uppercase See also: lcwords(), strtolower(), ucfirst(), d Match a digit character ucwords() D Match a non-digit character Strip HTML and PHP $input = You won the a href=http://www. s Match a whitespace character tags from a string example.comlottery!/a. $clean = strip_tags($input); S Match a non-whitespace character // $clean = You won the lottery! [] Enclose a character class See also: htmlentities(), htmlspecialchars() () Enclose a character grouping or define backreference Replace all $phrase = Big rockers listen to rock radio; $ Match end of line occurrences of a $phrase = str_replace(rock, talk, $phrase); substring // $phrase = Big talkers listen to talk radio ^ Match beginning of line See also: substr_replace(), strireplace(), . Match any character except for newline strtr() Quote the next metacharacter Return part of a string $description = WFAN: Sports Radio 66; as specified by an $callsign = substr($description, 0, 4); w Match any string containing underscore and alphanumeric offset See also: strrchr() characters W Match a string containing anything but underscore and Compare two strings if (strcasecmp(WTVN, wtvn) == 0) alphanumericl characters case-insensitively echo The strings are equal in a case- insensitive context. POSIX Regular Expression Functions See also: strncasecmp() PHP supports seven functions as defined by the POSIX 1003.2 Convert newline $stations = WTVN: 610nWLW: 700nWYTS: 1230; specification, including these commonly used solutions: characters to the $html = nl2br($stations); HTML br / tag // $html = WTVN: 610br /WLW: 700br /WYTS: int ereg(str $pattern, str $string Search $string for a $pattern. You can optionally 1230 [, array $regs]) include the $regs parameter, which will cause See also: htmlentities(), htmlspecialchars() an array of the same name to be returned containing each match. See eregi() for case- insensitive counterpart. string ereg_replace(str Replace any patterns found in string with REGULAR EXPRESSIONS $pattern, str $replacement, str replacement. See eregi_replace() for case- $string) insensitive counterpart. array split(str $pattern, str Split $string into an array, dividing it according PHP's regular expression features borrow heavily from both the $string [, int $limit]) to $pattern. See spliti() for case-insensitive Perl and POSIX formats, and in fact are formally identified as counterpart. such. POSIX Regular Expression Syntax Perl-compatible (PCRE) Regular Expression Functions [0-9] Any decimal digit from 0 - 9 PHP supports eight PCRE-specific functions, including these [a-z] Any character from lowercase a through lowercase z commonly used solutions: [A-Z] Any character from uppercase A through uppercase Z Function Description [A-Za-z] Any character from upper case A through lowercase z array preg_grep(str Searches $subject for $pattern, returning an array of p+ Any string containing at least one p $pattern, array $subject matches. The optional $flags parameter can be set to p* Any string containing zero or more p's [, int $flags]) PREG_GREP_INVERT, causing an array consisting of unmatched elements to be returned. p? Any string containing zero or one p p{N} Any string containing sequence of two p's int preg_match(str Determines whether $pattern exists in $subject. If p{N,M} Any string containing sequence of between N and M p's $pattern, str $subject [, $matches is defined, a similarly named variable will array $matches [, int be returned containing the matches. If $flags is set to p{2,} Any string containing sequence of at least two p's $flags [, int $offset]]]) PREG_OFFSET_CAPTURE, the string offset value will p$ Any string with p at the end of it also be returned for each match. See preg_match_all() for a variation of this function. ^p Any string with p at the beginning of it [^a-zA-Z] Any string not containing characters a-z through A-Z mixed preg_ Searches $subject for $pattern, replacing any replace(mixed $pattern, instances with $replacement. See preg_replace_ p.p Any string containing p followed by any character, followed by mixed $replacement, callback() for a variation of this function. another p mixed $subject [, int $limit [, int $count]]) Regular Expression Examples Validating a Phone Number Common PCRE Pattern Modifiers Presumes the required format is XXX-XXX-XXXX. Modifier Description // PCRE g Perform a global search if (preg_match('/^[2-9]{1}d{2}-d{3}-d{4}$/', '614- 599-2599')) i Perform a case-insensitive search echo Valid number!; m Treat the string as multiple lines ( // POSIX s Ignore newline characters if (ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', '614- x Ignore white space and comments 999-2599')) u Stop at the first match (ungreedy search) echo Valid number!; DZone, Inc. | www.dzone.com
  • 5. 5 PHP tech facts at your fingertips Validating a Username Telling Time with PHP, continued Presumes username is between 6 and 10 alphabetical and numerical characters. Month Parameters // PCRE F Full text representation of month if (preg_match('/^[a-z0-9]{6,10}$/i', '800gilmore')) m Numeric representation of month echo Valid username!; M Three letter textual representation of month // POSIX n Numeric representation of month, without leading zeros if (eregi('^[a-z0-9]{6,10}$', '800gilmore')) t Number of days in given month echo Valid username!; Year Parameters Turn URLs into hyperlinks L Whether date is a leap year // PCRE o ISO-8601 year number $text = Go to http://www.wjgilmore.com.; Y Full numeric representation of year $html = preg_replace('/s(w+://)(S+.?)(w+)/', y Two digit representation of year ' a href=123123/a', $text); // POSIX $text = Go to http://www.wjgilmore.com. ; Date Function Examples $html= ereg_replace('[a-zA-Z]+://(([.]?[a-zA- July 29, 2008 print date('F j, Y'); Z0-9_/-])*)', 'a href=00/a', $string); 7/29/08 print date('m/j/y'); // $html = Go to a href= http://www.wjgilmore. Today is Tuesday, July 29 10:45:21am printf(Today is %s, date('l, F j h:i:sa')); comhttp://www.wjgilmore.com. There are 31 days in July. printf(There are %d days in %s., date('t'), date('F')); TELLING TIME WITH PHP Setting the Timezone The Date Function You can set the timezone for all scripts by setting the date. timezone configuration directive within the php.ini file, or on The date() f unction is perhaps one of PHP's most commonly a per-script basis using the date_default_timezone_set() used functions, capable of retrieving nearly every temporal function. attribute of a specific timestamp. string date(string $format [, $int $timestamp]) Other Useful Functions a Lowercase Ante meridiem and Post meridiem Function Description A Uppercase Ante meridiem and Post meridiem int mktime([int $hour [, int $min [, int Returns the Unix timestamp for a given $sec [, int $month [, int $day [, int $year date B Swatch Internet Time [, int $is_dst]]]]]]]) c ISO 8601 date int time() Returns current timestamp e Timezone identifier string setlocale(int $category, string Sets the script locale g 12-hour hour format without leading zeros $locale) G 24-hour hour format with leading zeros int strtotime(string $time [, int $now]) Converts English textual date/time h 12-hour hour format with leading zeros description into a Unix timestamp H 24-hour hour format with leading zeros bool checkdate(int $month, int $day, Validates the date composed by the i Minutes with leading zeros int $year) $month, $day, and $year arguments. I Specifies whether date is in daylight savings time array getdate([int $timestamp]) Retrieves a timestamp as an associative array. Associative keys include seconds, O Difference to Greenwich time (GMT) in hours minutes, hours, mday (day of the P Difference to Greenwhich time (GMT) with colon between hours and month), wday (day of week), mon minutes (month), year, yday (day of the year), weekday, month, and 0 (seconds since r RFC 2822 date UNIX Epoch) s Seconds, with leading zeros T Timezone abbreviation PHP 5.1.0 introduced an object-oriented DateTime class. See u Milliseconds http://www.php.net/DateTime for more information. U Seconds since Unix Epoch Date-related Examples z Timezone offset in seconds Output December 25 $date = date('l', mktime(0,0,0,12,25,2008)); Day Parameters falls on a Thursday printf(December 25 falls on a %s, $date); d Day of month, two digits with leading zeros Output Next month is printf(Next month is %s, date('F', strtotime('+1 August. month'))); D Three letter textual representation of day Output Last Friday $date = date('F d, Y', strtotime('Last Friday')); j Day of month without leading zeros fell on July 25, 2008 printf(Last Friday fell on %s, $date); l Textual representation of day Output Oggi è setlocale(LC_ALL, it_IT); N ISO-8601 numeric representation martedì printf(Oggi egrave; %s, strftime(%A)); S Two character English ordinal suffix for day of month Retrieve a page's last- echo date('l, F j h:i:sa', filemtime($_SERVER[SCRIPT_ w Numeric representation of day of week modified date NAME])); z Numerical offset of day of year Calculate the $date1 = strtotime(2008-08-14); difference between $date2 = strtotime(2008-07-11); Week Parameters two dates $diff = $date2 - $date1; W ISO-8601 week number of year printf(Difference in days: %s, $diff / 60 / 60 / 24); DZone, Inc. | www.dzone.com
  • 6. 6 PHP tech facts at your fingertips Retrieving data as an indexed array: MYSQL INTEGRATION while ($row = $result-fetch_row() { printf(%S, $row[0]); Although PHP supports several popular databases, MySQL } remains by far the most common database solution. PHP's Retrieving data as an object: MySQL support has evolved considerably in recent years, with while ($row = $result-fetch_object() { the MySQLi (MySQL Improved) extension being the current printf(%S, $row-callsign); recommended solution. Here are the most commonly used } methods. Determining the Number of Rows Affected and Retrieved To determine the number of affected rows after sending an The PHP 5.3 release includes a new MySQL Hot INSERT, UPDATE, or DELETE query, use the affected_rows driver known as mysqlnd (MySQL Native Driver). Tip This driver eliminates the need for a previously property. required special licensing exception (FLOSS), and Example: eliminates the need to have MySQL installed on the same ma- $result = $mysqli-query(UPDATE stations SET station = '610' WHERE callsign = 'WTVN'); chine as PHP. It has already been integrated with the mysql printf(Rows affected: %d, $result-rows_affected); and mysqli extensions, with PDO support in the works. To determine how many rows were returned when using a SELECT query, use the num_rows property: Connecting to MySQL $result = $mysqli-query(SELECT * FROM stations WHERE state ='Ohio'); The mysqli extension provides a number of ways to connect to MySQL, but the easiest involves just passing the connection data printf(Rows affected: %d, $result-num_rows); along when instantiating the mysqli class: Working with Prepared Statements mysqli new mysqli([string host [, string user [, string pswd Prepared statements both optimize query performance and [string dbname [int port [string socket]]]]]]); decrease the possibility of SQL injection attacks by separating the query data from the logic, first passing the query to MySQL Here's an example: for preparation, binding variables to the query columns, and $mysqli = new mysqli(localhost, webuser, secret, corporate); finally passing the data to MySQL for query execution. To prepare a query, create the query, and then initialize a Handling Connection Errors statement object using the stmt_init() method: In case of connection error you can retrieve both the error $query = INSERT INTO stations VALUES(?, ?); number and error string using the errno() and error() $stmt = $mysqli-stmt_init(); methods. Example: if ($mysqli-errno) { Next the query is prepared by passing it to MySQL using the printf(Unable to connect: %s, $mysqli-error); prepare() method: exit(); $stmt-prepare($query); } Next, bind the parameters using the bind_param() method: Sending a Query to the Database $stmt-bind_param('ss', WTVN, 610); Once the connection has been established, you can begin Finally, execute the prepared statement using the execute() querying the database. Queries are sent using the query() method: method: $stmt-execute(); mixed query(string $query [, int $resultmode]) You can also use prepared statements to retrieve results. The Setting the optional $resultmode parameter to MYSQLI_USE_ general process used to execute the previous INSERT query is RESULT will cause query() to return the result as an unbuffered identical to that required for executing a SELECT query, except set. that the bind_param() method is not required, and you bind Example: results following a call to the execute() method. An example $result = $mysqli-query(SELECT callsign FROM follows: stations); $query = SELECT callsign, frequency FROM stations Sending INSERT, UPDATE, and DELETE queries works ORDER BY callsign; identically. For instance, sending an UPDATE query works like $stmt = $mysqli-stmt_init(); this: $stmt-prepare($query); $result = $mysqli-query(UPDATE stations SET station $stmt-execute(); = '610' WHERE callsign = 'WTVN'); $stmt-bind_result($callsign, $frequency); while ($stmt-fetch()) Retrieving Data printf(%s: %sbr /, $callsign, $frequency); Data can be parsed from the result set using a number of data structures, including via associative and indexed arrays, and Transactions objects. By default the MySQLi extension will render each query permanent upon successful execution, actually changing the Retrieving data as an associative array: while ($row = $result-fetch_array(MYSQLI_ASSOC) { database's contents when INSERT, UPDATE, and DELETE queries printf(%S, $row[callsign]); are processed. However the success of some tasks depend upon } the successful execution of several queries, and until all have DZone, Inc. | www.dzone.com
  • 7. 7 PHP tech facts at your fingertips Transactions, continued USEFUL ONLINE RESOURCES successfully executed, no changes to the database should actually occur. ATM transactions and online credit card processing are common examples requiring several queries. Using transactions, Resource Source you can change the MySQLi extension's behavior, committing a PHP Zone http://php.dzone.com series of queries as you see fit. The PHP Website http://www.php.net To begin a transaction, start by disabling the autocommit feature: Zend Developer Zone http://devzone.zend.com/ $mysqli-autocommit(FALSE); PlanetPHP http://www.planet-php.net/ Execute the various queries as you see fit, and if everything proceeds as you expect, execute the commit() method: PHPDeveloper.org http://phpdeveloper.org/ $mysqli-commit(); Developer.com http://www.developer.com/ Otherwise, if a problem occurs, execute the rollback() method: ONLamp PHP Devcenter http://www.onlamp.com/php/ $mysqli-rollback(); ABOUT THE AUTHOR RECOMMENDED BOOK W. Jason Gilmore Beginning PHP and MySQL is Jason Gilmore is founder of W.J. Gilmore, LLC, providing web development, the definitive book on the PHP consulting, and technical writing services to clientele ranging from publicly language and MySQL database. traded corporations to small startups. Jason is a prolific contributor to a Readers are treated to compre- number of leading publications such as Developer.com, Linux Magazine, hensive introductions of both and TechTarget, with almost 100 articles to his credit. He's cofounder of the technologies, and in addition to CodeMash conference (http://www.codemash.org/), a non-profit organiza- in-depth instruction regarding tion charged with organizing the annual namesake event. using these two technologies in Publications unison to build dynamic web sites. n Beginning PHP and MySQL n Beginning PHP and PostgreSQL 8 with Robert H. Treat n Beginning PHP and Oracle Website BUY NOW http://www.wjgilmore.com books.dzone.com/books/phpsql Get More FREE Refcardz. Visit refcardz.com now! Upcoming Refcardz: Available: Core Seam Essential Ruby Core CSS: Part I Core CSS: Part III Essential MySQL Struts2 JUnit and EasyMock Core .NET Hibernate Search Getting Started with MyEclipse Very First Steps in Flex FREE Equinox Spring Annotations C# EMF Core Java Groovy Core CSS: Part II NetBeans IDE 6.1 Java Editor XML PHP RSS and Atom JSP Expression Language Getting Started with JPA GlassFish Application Server ALM Best Practices JavaServer Faces Silverlight 2 Design Patterns Published June 2008 HTML and XHTML Visit refcardz.com for a complete listing of available Refcardz. DZone, Inc. 1251 NW Maynard ISBN-13: 978-1-934238-27-1 Cary, NC 27513 ISBN-10: 1-934238-27-9 50795 888.678.0399 DZone communities deliver over 4 million pages each month to 919.678.0300 more than 1.7 million software developers, architects and decision Refcardz Feedback Welcome makers. DZone offers something for everyone, including news, refcardz@dzone.com $7.95 tutorials, cheatsheets, blogs, feature articles, source code and more. Sponsorship Opportunities 9 781934 238271 “DZone is a developer’s dream,” says PC Magazine. sales@dzone.com Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, Version 1.0 photocopying, or otherwise, without prior written permission of the publisher. Reference: Beginning PHP and MySQL, Jason Gilmore, Apress, 2008.