Php Online Final
Upcoming SlideShare
Loading in...5
×
 

Php Online Final

on

  • 1,900 views

 

Statistics

Views

Total Views
1,900
Views on SlideShare
1,900
Embed Views
0

Actions

Likes
0
Downloads
46
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Php Online Final Php Online Final Document Transcript

  • Subscribe Now for FREE! refcardz.com tech facts at your fingertips CONTENTS INCLUDE: PHP ■ Configuration ■ Popular PEAR Packages ■ Object-Oriented PHP ■ Regular Expressions ■ MySQL Integration ■ 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. ■ Authoritative content For instance to change PHP's maximum allowable execution ■ Designed for developers time for a script tasked with uploading large files, you could call the ini_set() function from within your PHP script like so: ■ Written by top experts ini_set('max_execution_time', 60); ■ Latest tools & technologies ■ Hot tips & examples Changing the PHP File Extension PHP's default file extension is .php, however you can change it ■ Bonus content online to whatever you please by adding the desired extension to the ■ 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: Refcard 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=quot;quot;) { // 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(quot;The radio station %s has been destroyed!quot;, 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[quot;FMquot;][quot;WTVNquot;]; 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 quot;3 stations are being trackedquot; $stations = array ( printf(quot;%d stations are being trackedquot;, quot;WTVNquot;, quot;WBNSquot;, count($stations)); quot;WYTSquot;); Sorting Arrays $stations = array(); $count = array_push($stations, quot;WTVNquot;, quot;WBNSquot;, quot;WYTSquot;); 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(quot;%s<br />quot;, $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 quot;WTVNquot; => quot;610quot;, specifications of a user-defined $comparison_function) quot;WBNSquot; => quot;1460quot;, function, maintaining index quot;WYTSquot; => quot;1230 quot; 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 = quot;610quot; net/array. $channel = $stations[quot;WTVNquot;]; 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(quot;%s => %s<br />quot;, $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(quot;WTVNquot;,quot;WBNSquot;,quot;WYTSquot;); to a string $stations = implode(quot;,quot;, $stations) $stations = array( // $stations = quot;WTVN,WBNS,WYTSquot; quot;AMquot; => Converting a string $stations = quot;WTVN,WBNS,WYTSquot;; array(quot;WTVNquot; => quot;610quot;, to an array $stations = explode(quot;,quot;, $stations); // $stations[0]=quot;WTVNquot;, $stations[1]=quot;WBNSquot;, quot;WBNSquot; => quot;1460quot;, $stations[2]=quot;WYTSquot; quot;WYTSquot; => quot;1230quot;), Counting words in $sentence = quot;Columbus is home to numerous quot;FMquot; => radio stationsquot;; a string array(quot;WLVQquot; => quot;96.3quot;, $words = str_word_count($sentence); quot;WNCIquot; => quot;97.9quot;) // $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(quot;wtvnquot;); a string to B Match anything but word boundary // $callsign = quot;WTVNquot; uppercase See also: lcwords(), strtolower(), ucfirst(), d Match a digit character ucwords() D Match a non-digit character Strip HTML and PHP $input = quot;You won the <a href=quot;http://www. s Match a whitespace character tags from a string example.comquot;>lottery!</a>.quot; $clean = strip_tags($input); S Match a non-whitespace character // $clean = quot;You won the lottery!quot; [] Enclose a character class See also: htmlentities(), htmlspecialchars() () Enclose a character grouping or define backreference Replace all $phrase = quot;Big rockers listen to rock radioquot;; $ Match end of line occurrences of a $phrase = str_replace(quot;rockquot;, quot;talkquot;, $phrase); substring // $phrase = quot;Big talkers listen to talk radioquot; ^ 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 = quot;WFAN: Sports Radio 66quot;; 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(quot;WTVNquot;, quot;wtvnquot;) == 0) alphanumericl characters case-insensitively echo quot;The strings are equal in a case- insensitive context.quot; POSIX Regular Expression Functions See also: strncasecmp() PHP supports seven functions as defined by the POSIX 1003.2 Convert newline $stations = quot;WTVN: 610nWLW: 700nWYTS: 1230quot;; specification, including these commonly used solutions: characters to the $html = nl2br($stations); HTML <br /> tag // $html = quot;WTVN: 610<br />WLW: 700<br />WYTS: int ereg(str $pattern, str $string Search $string for a $pattern. You can optionally 1230quot; [, 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 quot;Valid number!quot;; 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 quot;Valid number!quot;; 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 quot;Valid username!quot;; 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 quot;Valid username!quot;; Year Parameters Turn URLs into hyperlinks L Whether date is a leap year // PCRE o ISO-8601 year number $text = quot;Go to http://www.wjgilmore.com.quot;; Y Full numeric representation of year $html = preg_replace('/s(w+://)(S+.?)(w+)/', y Two digit representation of year ' <a href=quot;123quot;>123</a>', $text); // POSIX $text = quot;Go to http://www.wjgilmore.com. quot;; Date Function Examples $html= ereg_replace('[a-zA-Z]+://(([.]?[a-zA- July 29, 2008 print date('F j, Y'); Z0-9_/-])*)', '<a href=quot;0quot;>0</a>', $string); 7/29/08 print date('m/j/y'); // $html = quot;Go to <a href=quot; http://www.wjgilmore. Today is Tuesday, July 29 10:45:21am printf(quot;Today is %squot;, date('l, F j h:i:sa')); comquot;>http://www.wjgilmore.com.quot; There are 31 days in July. printf(quot;There are %d days in %s.quot;, 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 quot;December 25 $date = date('l', mktime(0,0,0,12,25,2008)); Day Parameters falls on a Thursdayquot; printf(quot;December 25 falls on a %squot;, $date); d Day of month, two digits with leading zeros Output quot;Next month is printf(quot;Next month is %squot;, date('F', strtotime('+1 August.quot; month'))); D Three letter textual representation of day Output quot;Last Friday $date = date('F d, Y', strtotime('Last Friday')); j Day of month without leading zeros fell on July 25, 2008quot; printf(quot;Last Friday fell on %squot;, $date); l Textual representation of day Output quot;Oggi è setlocale(LC_ALL, quot;it_ITquot;); N ISO-8601 numeric representation martedìquot; printf(quot;Oggi &egrave; %squot;, strftime(quot;%Aquot;)); 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[quot;SCRIPT_ w Numeric representation of day of week modified date NAMEquot;])); z Numerical offset of day of year Calculate the $date1 = strtotime(quot;2008-08-14quot;); difference between $date2 = strtotime(quot;2008-07-11quot;); Week Parameters two dates $diff = $date2 - $date1; W ISO-8601 week number of year printf(quot;Difference in days: %squot;, $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(quot;%Squot;, $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(quot;%Squot;, $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(quot;UPDATE stations SET station = '610' WHERE callsign = 'WTVN'quot;); chine as PHP. It has already been integrated with the mysql printf(quot;Rows affected: %dquot;, $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(quot;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(quot;Rows affected: %dquot;, $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(quot;localhostquot;, quot;webuserquot;, quot;secretquot;, quot;corporatequot;); 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 = quot;INSERT INTO stations VALUES(?, ?)quot;; 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(quot;Unable to connect: %squot;, $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', quot;WTVNquot;, quot;610quot;); 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(quot;SELECT callsign FROM follows: stationsquot;); $query = quot;SELECT callsign, frequency FROM stations Sending INSERT, UPDATE, and DELETE queries works ORDER BY callsignquot;; identically. For instance, sending an UPDATE query works like $stmt = $mysqli->stmt_init(); this: $stmt->prepare($query); $result = $mysqli->query(quot;UPDATE stations SET station $stmt->execute(); = '610' WHERE callsign = 'WTVN'quot;); $stmt->bind_result($callsign, $frequency); while ($stmt->fetch()) Retrieving Data printf(quot;%s: %s<br />quot;, $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 quot;permanentquot; 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(quot;%Squot;, $row[quot;callsignquot;]); 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 MySQ 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. ■ Beginning PHP and MySQL ■ Beginning PHP and PostgreSQL 8 with Robert H. Treat ■ Beginning PHP and Oracle Website BUY NOW http://www.wjgilmore.com books.dzone.com/books/phpsql Want More? Download Now. Subscribe at refcardz.com Upcoming Refcardz: Available: Core CSS: Part II Published September 2008 Published June 2008 FREE ■ ■ Core CSS: Part III ■ Getting Started with JPA ■ jQuerySelectors ■ Core CSS: Part I ■ SOA Patterns ■ Flexible Rails: Flex 3 on Rails 2 ■ Struts 2 ■ Scalability and High Published May 2008 Published August 2008 ■ Agile Methodologies ■ Very First Steps in Flex ■ Windows PowerShell ■ Spring Annotations ■ C# ■ Dependency Injection in EJB 3 ■ Groovy ■ Core Java ■ Core .NET Visit http://refcardz.dzone.com ■ JUnit Published July 2008 for a complete listing of ■ MySQL ■ NetBeans IDE 6.1 Java Editor available Refcardz. ■ Seam ■ RSS and Atom Design Patterns ■ GlassFish Application Server Published June 2008 2008 ■ Silverlight 2 ■ IntelliJ IDEA 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 3.5 million pages per month to 919.678.0300 more than 1.5 million software developers, architects and designers. Refcardz Feedback Welcome DZone offers something for every developer, including news, refcardz@dzone.com $7.95 tutorials, blogs, cheatsheets, 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.