• Tidak ada hasil yang ditemukan

Beginning PHP and MySQL 5

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Membagikan "Beginning PHP and MySQL 5"

Copied!
953
0
0

Teks penuh

In the 18 months since the first edition of this book was published, the PHP and MySQL communities have continued to work feverishly to improve the capabilities of these two venerable technologies. Four additional chapters cover PHP 5's mysqli extension and MySQL 5's new stored routine, trigger, and view functionality.

Download the Code

That said, if you're interested in gaining practical and comprehensive insight into the PHP programming language and the MySQL database server, and how these prominent technologies can be used together to create dynamic, database-driven web applications, this book is for you. Furthermore, both beginners and experienced PHP and MySQL developers have something to gain from this book, as I have purposely organized it in a hybrid format of both tutorial and reference.

Contact Me!

This information sets the stage for a discussion of PHP's feature set, including the new features of PHP 5. What PHP's developers have done to once again reinvent the language, making version 5 the best yet released.

History

In early 1999, Netcraft (http://www.netcraft.com/) reported a conservative estimate of the user base that made PHP one of the most popular scripting languages ​​in the world. On May 22, 2000, approximately 18 months after the first official announcement of the new development effort, PHP 4.0 was released.

General Language Features

This strategy was adapted in version 5, in which a specialized string offset syntax was introduced and the previous methodology was abandoned. Improved XML and Web Services Support: XML support is now based on the libxml2 library, and a new and quite promising XML parsing and processing extension known as SimpleXML has been introduced.

Practicality

Power

Possibility

Price

Summary

In this chapter you will learn how to install and configure PHP, including how to install the Apache web server. How to install Apache and PHP as an Apache server module on both Unix and Windows platforms.

Installation

How to test your installation to ensure that all components are working properly. The purpose, scope, and default values ​​of many of PHP's most commonly used configuration directives.

Obtaining the Distributions

If you plan to use PHP in conjunction with Apache on Windows, you should download this distribution, as it is the focus of the later installation instructions. Keep in mind that some of the versions made available via this website are not intended for production use.

The Installation Process

Also note that there is another default configuration file at your disposal, recommended by php.ini. Also note that there is another default configuration file at your disposal, recommended by php.ini.

Figure 2-1. Modifying the Windows Path
Figure 2-1. Modifying the Windows Path

Testing Your Installation

Rename the php.ini-dist file php.ini and save it in the C:\php5 directory. The php.ini file contains hundreds of directives responsible for customizing PHP's behavior.

Customizing the Unix Build

To make adjustments to the build process, you just need to add one or more of these arguments to PHP's configure command, including a value assignment if needed. For example, suppose you want to enable PHP's FTP functionality, a feature that is not enabled by default.

Customizing the Windows Build

Please note that you will also need to install the software that is ultimately responsible for enabling the extension support. In the case of the Java example, you need the Java Development Kit (JDK).

Common Pitfalls

For example, if you've only defined .php as a recognizable extension, don't try to embed PHP code in an .html file. You have created a file called index.php and are unsuccessfully trying to call it as you would a standard directory index.

Viewing and Downloading the Documentation

Verify that the file ends with a PHP-specific suffix as specified in the httpd.conf file.

Configuration

Managing PHP’s Configuration Directives

PHP_INI_PERDIR: The directive can be changed in php.ini, httpd.conf or .htaccess files. PHP_INI_SYSTEM: The directive can be changed in the php.ini and httpd.conf files.

PHP’s Configuration Directives

Disabling display_startup_errors prevents the user from seeing errors specific to PHP's startup process. While disabling register_globals is definitely a good idea, it's not the only factor you should keep in mind when securing an application.

Table 2-1. PHP’s Error-Reporting Levels
Table 2-1. PHP’s Error-Reporting Levels

Escaping to PHP

This material laid the groundwork for what will be the core of much of the remaining material in this book: building powerful PHP applications. How to delimit PHP code, which provides the parsing engine with a means of determining which parts of the script to parse and execute and which to ignore.

Default Syntax

Short-Tags

Script

ASP-Style

Embedding Multiple Code Blocks

Comments

Single-line C++ Syntax

Shell Syntax

Multiple-line C Syntax

Output

In this last variant, three strings were concatenated using a dot, known in this context as the concatenation operator.

Sometimes it is convenient to change the order of execution of the arguments, or repeat the execution of a particular argument, without explicitly repeating it in the argument list.

Datatypes

Scalar Datatypes

An integer is simply a whole number or one that contains no fractions. Such groups are usually delimited by single or double quotes, although PHP also supports another delimitation methodology, which is introduced in the later section "String Interpolation". This section also discusses the implications of all three delineation methods.

Compound Datatypes

Unlike other data types included in the PHP language, an object must be explicitly declared. Therefore, in the last line of the previous listing, an appliance class object named blender is created.

Special Datatypes

If you are new to object-oriented programming, don't worry, because Chapters 6 and 7 are devoted to a complete introduction to the subject. Variables of type resource do not actually have a value; rather, they hold a pointer to the opened resource connection.

Type Casting

In fact, if you try to export the content, you will see a reference to a resource ID number. Note that the double will be rounded down each time, regardless of the decimal value.

Type Juggling

The result is the expected one; $total is set to 20, converting the $count variable from a string to an integer to do so. Because the original string $total starts with an integer value, that value is used in the calculation.

Type-Related Functions

In this example, a string is converted to type Boolean to evaluate the if statement.

Type Identifier Functions

Identifiers

An identifier can consist of one or more characters and must start with a letter or an underscore. In addition, identifiers can only consist of letters, numbers, underscores, and other ASCII characters from 127 through 255.

Variables

This is useful because it enables a programmer to accurately describe the purpose of the identifier via the identifier name.

Variable Declaration

Assignment by value simply means that the value of the assigned expression is copied to the assignee variable. You can assign variables by reference by adding an ampersand (&) to the equals sign.

Variable Scope

Parameters passed by reference will indeed be affected by any changes made to the parameter from within the function. To modify a global variable, however, it must be explicitly declared as global in the function in which it is to be modified.

PHP’s Superglobal Variables

You can display just one of these variables simply by treating it as an ordinary variable. Note To use predefined variable arrays, the track_vars configuration parameter must be enabled in the php.ini file.

SERVER

POST

Like $_GET, the $_POST superglobal is by default the only way to access POST variables.

COOKIE

FILES

REQUEST

SESSION

GLOBALS

Variable Variables

Constants

Expressions

Operands

Operators

The bitwise operators listed in Table 3-12 are variations of some of the logical operators, but can result in drastically different outcomes. If you are interested in learning more about binary coding, bitwise operators and why they are important, check out Randall Hyde's massive online reference, "The Art of Assembly Language Programming", available at http://webster.cs.ucr.edu / .

Table 3-4. Arithmetic Operators
Table 3-4. Arithmetic Operators

String Interpolation

Double Quotes

It's worth pointing out that this result is found in the browser feed, not the browser window. But if you look at the source, you'll see that the output actually appears on two separate lines.

Single Quotes

In this case, the backslash appearing at the end of the string had to be escaped, otherwise the PHP parser would understand that the trailing single quote needed to be escaped. However, if the backslash appeared anywhere else in the string, it would not need to be escaped.

Heredoc

Omitting the backslash escape character results in a syntax error unless the magic_quotes_gpc configuration statement is enabled.

Control Structures

Execution Control Statements

Conditional Statements

The problem with the previous example is that output is only presented to the user who guesses the secret number correctly. To do this, you'll need a way to handle those that don't meet the if conditional requirements, a function conveniently provided by way of the else statement.

Looping Statements

The do..while loop condition is a version of the while loop, but it checks the loop condition at the end of the block rather than at the beginning. The first expression, expression1, is evaluated by default on the first iteration of the loop.

File Inclusion Statements

First, the file will be included in the script in which the require() construct occurs, regardless of where require() is located. Although this may not always be a problem, sometimes you will not want changed variables in an include file to be overwritten by a later include of the same file.

Invoking a Function

For example, in an e-commerce application, you may need to request a customer's profile information multiple times: at check-in, at checkout, and when verifying a shipping address. You may need to sift through each page of the application, modifying the query as necessary, likely introducing errors in the process.

Creating a Function

Passing Arguments by Value

If you want these changes to be reflected outside the scope of the function, you can pass an argument by reference presented next. Note Note that you don't necessarily need to define a function before it is called because PHP reads the entire script into the engine before executing it.

Passing Arguments by Reference

Once you define the function, you can then call it, as demonstrated in the previous section. This means that any changes made to those values ​​within the scope of the function are ignored outside the function.

Default Argument Values

Optional Arguments

If multiple optional arguments are provided, you can selectively choose which ones are passed.

Returning Values from a Function

Nesting Functions

For example, suppose you want to create a function that retrieves user data from a database, say the user's name, email address, and phone number, and returns it to the caller.

Recursive Functions

Variable Functions

In particular, an attacker could execute any function in PHP's repertoire simply by changing the variable used to declare the function name. For example, consider the consequences of changing the $trigger variable in the previous example to contain the value exec and changing the $rowid variable to contain rm -rf.

Function Libraries

The next chapter introduces PHP's array functionality, covering the language's vast array of management capabilities and introducing PHP 5's new array handling features. PHP's solution is no different, supporting the array data type, in addition to an associated set of behaviors and functions aimed at array manipulation.

What Is an Array?

The array pointer acts like a bookmark and tells you the position of the array you are currently examining. You will not work directly with the array pointer, but instead will traverse the array using either built-in language features or functions.

Outputting Arrays

As you will learn in this chapter, PHP provides many ways to traverse an array. Tip The print_r() function is not the only way to print an array, but it provides a convenient way to do so.

Creating an Array

The array() function takes as its input zero or more items and returns an array consisting of these input elements. The range() function provides an easy way to quickly create and fill an array consisting of a range of low and high integer values.

Testing for an Array

The optional step parameter provides a convenient way to determine the increment between members of the array.

Adding and Removing Array Elements

The array_shift() function is similar to array_pop() except that it returns the first array element found on the target_array instead of the last. The array_pad() function modifies the target array and increases its size to the length specified by length.

Locating Array Elements

The array_key_exists() function returns TRUE if the given key exists in the target_array array, and returns FALSE otherwise. The array_values() function returns all the values ​​set in the target_array array, automatically providing the numeric indices for the returned array.

Traversing Arrays

The current() function returns the array value that resides at the current pointer position of the target_array. The next() function returns the array value at the position immediately following that of the current array pointer.

Determining Array Size and Uniqueness

The function array_flip() flips the roles of the keys and their corresponding values ​​in the array target_array. The array_unique() function removes any duplicate values ​​found in input_array, returning an array consisting entirely of unique values.

Sorting Arrays

Returning to the file sorting dilemma raised in the natsort() section, suppose the pictures were named like this: Picture1.JPG, picture2.jpg, PICTURE10.jpg, picture20.jpg. If the optional sort_flags parameter is included, the exact sorting behavior is determined by its value, as described in the sort() section.

Table 5-1. array_multisort() Flags
Table 5-1. array_multisort() Flags

Merging, Slicing, Splicing, and Dissecting Arrays

If length is specified and is positive, it ends at offset + length positions from the beginning of the array. If length is specified and is positive, the split will end at offset + length positions from the beginning of the array.

Other Useful Array Functions

This chapter and the next introduce what is undoubtedly the shining star of PHP 5: the vast improvements and enhancements to PHP's object-oriented functionality. Note While this and the following chapter are intended to give you a comprehensive introduction to PHP's OOP functions, a thorough discussion of their implications for the PHP developer is actually worth an entire book.

The Benefits of OOP

Encapsulation

Inheritance

Each of these specific employee classes, in turn, can inherit from another, more specific class. For example, the "employee" type can inherit from a day worker and a night worker, each of which inherits all the traits specified by both the worker definition and the worker definition.

Polymorphism

To build on this idea, you can later create a "human" class, and then make the "employee" class a subclass of human. The effect would be that the employee class and all its derived classes (clerk, cashier, CEO, and so on) would immediately inherit all human-defined properties and behaviors.

Key OOP Concepts

Classes

Don't worry if you're unfamiliar with some of the grammar and syntax (especially private/protected and $this); each of these topics is discussed in detail later in the chapter.

Objects

Once the object is created, all the features and behaviors defined within the class are made available to the newly instantiated object.

Fields

The first four are introduced in this section, and the static scope is discussed in the later section, "Static Class Members". You can also declare methods as final; the procedure for doing this is described in the later section, "Methods".

Properties

Marking a field as final prevents it from being overridden by a subclass, a matter discussed in more detail in the next chapter.

Tip In the case of public methods, you can dispense with the explicit declaration of the scope and just declare the method as you would a function (without any scope). Note The topics of class inheritance and overriding methods and fields are discussed in the next chapter.

Type Hinting

Constructors and Destructors

Constructors

Instantiating the book object results in the automatic invocation of the constructor, which in turn calls the setIsbn(), getTitle(), and getNumberCopies() methods. Calling the Staff constructor this way results in the same outcome as shown in the previous example.

Destructors

As an example, assume that the Manager and Staff classes used in the previous example have no hierarchical relationship; instead, they are simply two classes nested within the same library. Therefore, if the instantiated class and any information created as a result of the instantiation resides in memory, you are not required to explicitly declare a destructor.

Static Class Members

However, if the instantiation has created less volatile data (say stored in a database) and should be destroyed at the time the object is destroyed, you will need to create a custom destructor. Also note that you refer to static fields and methods using the self keyword and class name instead of using the this and arrow operators.

The instanceof Keyword

Since the $visitors field has been declared static, any changes to its value (in this case via the class constructor) are reflected in all instantiated objects. This is because referencing static fields with resources that are allowed for their "regular" siblings is not possible and will result in a syntax error if you try.

Helper Functions

The get_class_vars() function returns an associative array containing the names of all fields and their corresponding values ​​defined in the class specified by class_name. The is_subclass_of() function returns TRUE if the object belongs to a class inherited from class_name and returns FALSE otherwise.

Autoloading Objects

The is_a() function returns TRUE if the object belongs to a class of type class_name, or if it belongs to a class that is a child of class_name. The method_exists() function returns TRUE if a method named method_name is available for the object, and returns FALSE otherwise.

Advanced OOP Features Not Supported by PHP

Method Overloading: The ability to implement polymorphism through function overloading is not supported by PHP and, according to a discussion on the Zend website, probably never will be. Only time will tell if any or all of these features will be supported in future versions of PHP.

Object Cloning

Operator overload: The ability to assign additional meanings to operators based on the type of data you are trying to change has failed this time. According to the aforementioned discussion on the Zend website, this feature is unlikely to ever be implemented.

Cloning Example

As you can see, $drone2 has become an object of type corporatedrone and inherited the member values ​​of $drone1. To further demonstrate that $drone2 is indeed of type corporatedrone, its employee member is also reassigned.

The __clone() Method

These characteristics and behaviors would be relevant to all types of employees, regardless of the employee's purpose or status within the organization. An assistant should be able to take a memo and an office manager should take supply inventories.

Class Inheritance

Because all employees are named, the Executive class inherits from the Employee class, saving you the trouble of having to recreate the name member and associated getter and setter. This method is only available for objects of type Executive, and not for the Employee class or any other class, unless of course we create a class that inherits from Executive.

Inheritance and Constructors

If you want the Employee and Executive constructors to fire, you must call parent::__construct() in the Executive constructor. For example, suppose the Employee and Executive constructors should be executed when a new CEO object is created.

Interfaces

Gambar

Figure 2-1. Modifying the Windows Path
Figure 2-2. Output from PHP’s phpinfo() function
Table 2-1. PHP’s Error-Reporting Levels
Figure 3-1. Sample PHP Output
+7

Referensi

Dokumen terkait

called special-purpose funds.. Click to edit Master title style Example Exercise 8-4. Prepare journal entries for each of

Figure 6.15 This join returns every column from both tables where the forum_id values represent the kindling forum (6). Figure 6.16 Generically referring to a column name present

In addition, blended learning is very useful for learners in learning English because that enables them to practice language inside and outside the class room, which enhances their