PHP Basics
First, the initial knowledge of PHP
PHP is an embedded language that is used in combination with HTML.
1, PHP tags
The default tag <?php?> short mark.??, you need to turn on the Short_open_tag option to open short and other tags in php.ini is not recommended
2, the keyword is not case-sensitive, user-defined class name and function name are not case-sensitive, variable names are case-sensitive
3, output
Boolean print (parameter) returns a bool
void echo (parameter) No return value echo has a higher efficiency.
Ii. Types of data
1. The usual way to compare two floating-point numbers is to move a number of decimal places first and then convert to integer data for comparison.
2, double quotes do delimiter string support variable name resolution, single quote delimiter string does not support variable name resolution.
$name = "John";
"$name" => John | | ' $name ' => $name | | "Mr. $name" => Empty | | "{$name}" Mr. => John | | "${name}" Mr. => John
3, the way the string is defined: single quotes, double quotes and Heredoc (<<
4, the object type must be explicitly declared. Class with the keyword class definition, using the keyword new to generate an instance of this class, using the-> symbol class to access the properties and methods in the class
Class Car{public $COLOLR; function beep () {}} $mycar = new car; $mycar->color= ' red '; $mycar->beep ();
5, PHP is a weak language type, the type of the variable will be given by the value of their own determination, and often in the declaration of variables at the same time the variable initial value assignment.
6, when data type casts, only the type name required should be written in parentheses in front of the variable.
Three, constants and variables
1, define constant define ("constant name", expression or value) constant name recommended all uppercase, but not required
Use constants to directly use a defined constant name without adding "$" to the constant name
Predefined constants: _file_ the current PHP program file name _line_ the number of rows in the current PHP program (where to refer to)
2, the variable does not need an explicit declaration, when the variable is assigned to the initial value of the variable is declared. If the variable is not set to an initial value, the initial value is null.
3, Variable assignment: value assignment and reference assignment. such as $a=& $b; That is, b originally pointed to a storage location, after referencing the assignment, a also points to the storage location,
The destruction of a or B will have no effect on the other side, but if one of the values changes, the other will make the same change.
4, access to predefined variables using the Super global variable, a total of 9 super global variables
5. Local variables: variables defined within a function can only be used within a function
Global variables: Variables defined outside a function can only be used outside of a function by default
To use a global variable within a function, you need to declare the variable in global, or use a &globals[array to "variable name"
In PHP, only functions can provide a local scope.
The Super global variable $globals contains all the variables
The characteristic of a static variable: it is initialized only the first time it is invoked, the function does not destroy after it is finished, and the variable retains its original value the next time it is used.
Static variables can only be defined and used within functions.
Variable variable: the name of the variable is also used as a variable. $a =b $b =c;$ $a = $b =c;
External variables: The maximum number of data that can be passed with a Get method is 256 bytes, and the maximum is 2MB with post
Iv. Process Control (write only to different languages, such as Java)
1, interactive format (colon syntax) is not recommended, the classic more intuitive
2, foreach (): This syntax is specifically designed for arrays
First format foreach (Target_array as $value) statement
The second format foreach (Target_array as $key => $value) statement
3, break number: The number of layers to jump out of the structure
CONTIUE Number: The number of layers to jump out of the structure
4, the Exit statement can end the current execution of the entire script, usually for error checking.
Exit Exit ("Cause of error");
Die () is the alias of exit $conn =mysql_connect ("localhost", "root", "") or Die ("Unable to connect to the MySQL server");
Five, array
1. The only difference between an associative array and a numeric index array is the type of index.
2, Digital Index array
Initializing: Assigning an array () function directly to an array element
If the array does not exist, then the array element is assigned a value and can be created
If the array element is a sequential number, you can use the range () function when initializing the arrays
Range () has 3 parameters, the first parameter specifies the initial value, the second parameter specifies the ending value, and the third parameter is optional, which specifies the step size
3. Associative array
Initializing: Assigning an array () function directly to an array element
4, the array-related operators
+ Union $a + $b after the $ attachment to $a, but any elements that conflict with the index value will not be added
= = equals $a = = $b If $a and $b contain the same elements, return True (index values and elements must be identical) except in order, others must be exactly the same
!= <> Not equal to
= = Identity if $a and $b contain the same elements in the same order, return True (index values and elements must be identical) must be exactly the same
!== not identical
5, sorting the array
The Boolean sort () is assigned a new index value and the original index value is deleted, sorted by number and alphabetical order
void Asort () preserves the original index relationship by sorting the array in ascending order
Integer ksort () arranged in ascending order of index value
Usort (array, method name) sorted by user custom method
Array_multisort () to sort multiple arrays at once
Natsort () sorted in natural order, preserving the original index relationship after sorting
Natcasesort () natural sort, case-insensitive
6, the reverse ordering of the array
Rsort () array elements in descending order
Arsort ()
Krsort ()
7. Reorder the arrays
Boolean shuffle () random permutation of arrays
Array array_reverse () to invert the elements in an array
Array Array_flip () converts an index in an array to its element value
8, the array of traversal
Current () Gets the value of the element that is being referred to in the array
Next () Moves the pointer of the array back one bit, returning the element value of the element to which the pointer points after moving
Prev () Moves the pointer of the array forward one bit, returning the element value of the element to which the pointer points after the move
Reset () pointer set back to the starting position of the array
End () Moves the pointer to the last element of the array
Each () returns the index/element value pair that the current pointer points to in the array and moves the array pointer backward one
Returns an array that contains 4 elements, and the index of the array is 0,key,1,value, respectively.
Key () returns the index value that the current pointer of the array points to
Array_walk () Handles each element of the array in the same way
Array_reduce () applies the custom function to each element of the array in turn
9. Other array operation functions
List () extracts multiple values at once from an array and assigns values to multiple variables at the same time
Count ()/sizeof () calculates the number of elements in an array
Six, the string in PHP
1, access to characters in the string
Three ways to define strings: single quotes, double quotes, and Heredoc
You can treat a string as an array. $test = "Hello"; $test {0}= "H"; the use of curly braces is recommended to avoid confusion with arrays
2, the format of the string
The formatting of strings usually includes removing extra space in the string, capitalization conversion, adding and removing backslashes, and HTML formatting four parts
Remove spaces and other symbols
String Trim (string to be processed, filter string)
If you do not specify a filter string, remove spaces, tab characters, line breaks, carriage returns, string terminators, and Vertical tabs by default
You can use the ".." Specifies a range that needs to be removed, for example, "a." F "means to remove a, B, C, D, E and F
Filters only the end and end characters of a string, even if a filter string is specified, the middle part of the string is not involved in filtering
String Lrtim (strings to be processed, filter strings)
Remove space and other special characters to the left of the string
Other with Trim ()
String RTrim (string to be processed, filter string), alias function chop ()
Remove spaces and other special characters to the right of the string
Other with Trim ()
Conversion of strings to uppercase and lowercase
Strtolower (the string to be processed) converts all characters in the specified string to lowercase
Strtoupper (the string to be processed) converts all characters in the specified string to uppercase
Ucfirst (the string to be processed) checks the specified string and converts it to uppercase if the first character of the specified string is a letter
Ucword (the string to be processed) converts the first letter of each word in the specified string to uppercase
Add and remove backslashes
You should use the Addslashes () function to add a backslash before you save any string to the database;
Before displaying user data, you should call the Stripslashes () function to remove the backslash
Addslashes (the string to be processed) add back slash
Stripslashes (the string to be processed) remove the backslash
HTML formatting
NL2BR (the string to be processed) can convert a newline character in a string to the label "<br>" in HTML to implement a newline in the browser
Htmlspecialchars (the string to be processed, whether to convert double quotes and single quotes, character sets)
You can make some special characters as normal text output without parsing HTML again
The second argument: the default is to convert only double quotes, Ent_compat convert only double quotes ent_quotes
Ent_noquotes not to convert
Third parameter: Specifies the character set to use when converting, default to Iso-8859-1
Hemlentities (the string to be processed, whether to convert double quotes and single quotes, character sets)
Function ditto, but can escape more special characters
Heml_entity_decode (the string to be processed, whether to convert double quotes and single quotes, character sets)
You can reverse-convert the display string, and the converted string can be parsed by an HTML tag
Strip_tags (the string to be processed, HTML tags allowed to be preserved)
Get rid of all HTML and PHP tags
3. Connection and segmentation of strings
Explode (delimiter, string, number of fragmented string fragments) splits a string by the specified delimiter
If the delimiter is a string, the function is divided according to each character in the string, not the entire split string
Implode (connectors, which need to be concatenated into an array of strings) to concatenate some strings into a string by a specified connector
Join (a connector that needs to be connected to an array of strings) features the same implode ()
SUBSTR (string, start position, fetch length) extract part of substring from a string
The start position is negative, and you get a substring starting at the end of the original string with a length of the absolute value of the negative number
The extraction length is negative and the substring is taken before the penultimate "length" character
This is not difficult to understand,-it means starting from behind
Strtok (string, delimiter) remove a string fragment from the specified string
If the delimiter is a string, the function is divided according to the first character in the string, not the entire string.
When the function is called to split the string continuously, only the first partition needs to specify the parameter str, and after the first partition, the system automatically
The record string and the first segmented pointer position, and continue to call the function, and continue to split from the current position of the string pointer
。 If you want to reset the pointer to the start of the string, simply pass the string back as a parameter to the function.
Split (delimiter, string, return number of strings) decompose a string into multiple substrings by the specified delimiter
4. Comparison of strings
You can compare strings directly by using = =
strcmp (String 1, String 2) in dictionary order, in the back of the large. If equal, returns 0, if STR1 is greater than str2, returns a positive number, otherwise the negative number
Case sensitive
STRCASECMP (String 1, String 2) ditto, case-insensitive
STRNATCMP (String 1, String 2) is a string comparison in natural order, equal to 0, greater than the return positive number, less than the return negative, case-sensitive
STRNATCASECMP (String 1, String 2) is compared in natural order, case-insensitive
5, find and replace the string
Strstr (the string being searched, keyword to find a matching string or character in a string, and if found, returns a substring from the beginning of the STR character to the end of the string, or false if not found, and returns from the first match to the knot Substring of tail
Strisstr () function ditto, difference, this function is case-insensitive
STRCHR (the string being searched, keyword to look up in a string to find a substring or character to match, starting at the end of the string and, if found, returning the substring from the key to the end of the string, or, if more than one, returning the first match starting at the end. If no match is returned, false
Strpos (The string to find, a substring or character to find, starting with the offset character of the original string)
If one is found, return the position, starting from 0, if more than one, return the first, if not, return flase
Offset cannot be negative, otherwise the lookup cannot start
Strrpos (the string to be searched for, the keyword to find, starting with the first offset character of the original string)
To find from the end of a string, if more than one, returns the penultimate match
Strripos (The string to find, the keyword to find, starting with the first offset character of the original string)
function with Strrpos (), difference is not case-sensitive
Stripos (The string to find, the keyword to find, starting with the first offset character of the original string)
Features are not case-sensitive compared to Strpos ()
Str_replace (replaced string or array, replacement string or array, source string or array, number of substitutions)
Searchreplacesubject
Replaces search in subject with replace
If search is an array, replace is a string, and replace replaces all elements in the search array
If both search and replace are arrays, the elements in replace replace the corresponding elements in search
If the number of elements in the search array is redundant, the elements in the extra search array are replaced with empty strings
Substr_replace (the original string to be manipulated, the string to replace, the starting position of the original string to be replaced, the number of characters in the original string being replaced) to find and replace a specific substring in a string at a specified location
Start position: If positive, start from scratch, if negative, start at end of calculation
Length: If positive, indicates that the consecutive length characters starting from Start are replaced,
If negative, indicates that the character is replaced from start to the penultimate length
Str_ireplace () function is the same as Substr_replace (), but the function is case-insensitive
6. Other common String functions
Strlen (String) to calculate the length of the specified string
MD5 (strings, flags) encrypt a string MD5 algorithm
The second argument, if true, returns a 16-bit binary number and, if False, returns a 32-bit hexadecimal string, which defaults to False
Object-oriented programming technology in PHP
1, the characteristics of the object
Encapsulation: An object is the most basic unit of encapsulation, a data structure encapsulated by an object name, and a collection of operations that can be applied to those data.
Like a box, we don't need to know what's in the box, just know what it's for.
Inheritance: PHP does not support multiple inheritance, which is essentially code reuse, which means that subclasses can automatically have all the attributes of the parent class without having to build from scratch.
Polymorphism: The ability to use the context of a class to redefine or change the behavior of a class. Polymorphism enables an object to decide which behavior or method to perform according to the parameters it obtains, while providing a unified interface to the external.
2, the structure of the class
Class name
{
Defining attributes, using the keyword var
var $var 1;
var $var 2;
...
Defining methods, using keyword function
function Method1 (...) {...}
function Method2 (...) {...}
...
You cannot define a class separately to multiple PHP tag pairs, or you can define them separately in multiple files.
3. Instantiation of Class
To create an instance of a class by using the keyword new
$ instance Name =new class name;
4, using the properties of the class
To use a property or method defined in a class, simply use the operator "->". You need to use the $this pointer if you need to access the properties or methods that are defined internally within the class when you define the class.
In general, there is a risk of accessing the class's properties directly from outside the class, and PHP provides some protection against accessing class properties. __set (), __get (), when the view references a
Property that does not exist in the class, these methods are called to handle the corresponding processing.
5, classes of access control control class properties and methods
If you specify an access control type for the properties of a class, the keyword VAR needs to be omitted
Public can be accessed both inside and outside of the class. This option is the default option.
Use the ':: ' operator to access a function or variable in a class without creating an instance of any class
The format is as follows: Class Name:: Function class Name:: Variable
Private can only be accessed inside a class
Protected can only be used in this class and its subclasses
6. Constructor function
The constructor is invoked automatically when a class is instantiated. PHP does not support multiple constructors.
The syntax format of the constructor is as follows: function __construct (parameter 1, parameter 2, ...) {}
7. destructor function
Destructors are called before the class object is destroyed, and are typically used to set up some of the actions to be done before the object is destroyed. The easiest way to destroy an object is to assign it a null value directly
destructor Syntax: function __destruct () {}
At the end of the script, PHP automatically destroys all objects in memory. Therefore, you do not need to explicitly define a destructor for a generic class object.
But if the class object creates data that is not easily destroyed when it is instantiated, if the data is stored in the database rather than in memory, you should define a destructor, in the class
This data can be destroyed properly when the object is destroyed.
8. Static properties and methods
Static properties and methods need to be referenced by using the keyword "self::", and other introductory text already has
9, class operator instanceof
You can tell if an object is an instance of a class
10. Inheriting existing classes
Inheritance using keyword Extend
11, Class of overload
Overloading is the definition of the same properties and methods as the parent class in subclasses. Class allows a property to be assigned a value that is not the same as the parent class in a subclass.
You can also assign a method to a function that is not the same as its parent class.
12. Accessing properties and methods in the parent class
A subclass can inherit and overload the properties and methods in the parent class, and can override inherited properties and methods. But sometimes, in subclasses, you need to directly
Invokes a method in the parent class. You can use the keyword "Parent::" in PHP to achieve access to properties and methods in the parent class.
13. Use final keyword to prohibit inheritance and overload
When the keyword "final" is used before a function definition, it means that the function will not be overloaded by any subclass.
If you do not want a class to inherit, simply add the final keyword to the class when you define it
If a property or method in a class is specified as "private," the property or method cannot be inherited
If a property or method in a class is specified as "protected", the property or method can be inherited by the quilt class, but it cannot be accessed directly outside the class
If a property or method in a class is specified as "public," the property or method is not only inherited by the quilt class, but can be accessed anywhere
14. Abstract classes and abstract methods
Abstract classes are classes that cannot be instantiated and can only be used as parent classes of other classes. So subclasses of an inherited abstract class must implement all of the abstract methods.
Use the keyword "abstract" in PHP to define an abstract class and method.
15, interface
An interface is a special abstract class that typically contains only abstract methods and does not define attributes. The definition of the attribute and the implementation of the abstract method are done to the class that implements the interface.
Define the interface using the keyword "interface" to implement the interface using the keyword "implements"
16. Implement multiple interfaces
Classes in PHP do not allow multiple inheritance, but allow multiple interfaces to be implemented
17, the assignment of the object
Target object = Clone original object; Duplicate two objects exactly the same, but do not interfere
You can also use the __clone () method to adjust the behavior of an object assignment in PHP. By default, this function creates an object that has the same properties and methods as the original object, if you want to
After you assign a value to change something in the original object, simply rewrite the corresponding properties and methods in the original object in the method. This method can use the $this pointer
18, Automatic loading class
PHP specifically provides the __autoload () function to automatically load the required classes.
When loading is required, the function is automatically invoked, and the class name is passed to the __autoload () function as a parameter
19, processing does not exist method calls
When a method that does not exist in the calling class will produce a fatal error, PHP provides the __call () method to handle this type of error.
20. Serialization of objects
In order to facilitate the transfer and storage of variables, it is usually converted into a byte stream of strings before the variables are transmitted and stored, and then restored to the
The original variable, the process becomes serialized and deserialized.
To facilitate the transfer and storage of class objects, you can also align for serialization and deserialization processing. The function serialize () is used in PHP to serialize an object whose arguments are object names.
The returned value is the string that was obtained after serialization. Deserialization uses the Unserialize () function, whose argument is a string that returns the original object.
When the object is serialized, it automatically calls a __sleep () method, completes some bedtime, does not receive any arguments, but returns an array of
Specifies the property that needs to be serialized, and the properties that are not included are ignored when serialized. If you do not specify the __sleep () method, PHP serializes all of the properties.
When an object is deserialized, it automatically invokes a method named __wakeup () to do what the object wakes up to do.
Eight, PHP access to the MySQL database
1. Basic steps of database operation
Linked database server mysql_connect (MySQL server host name, username, password);
Select a database mysql_select_db (database name, resource identifier);
Operation of the database mysql_query (database statement, resource identification);
Processing of data records mysql_fetch_row (resource identification);
2. Connect and close the database
$connect = mysql_connect ("localhost", "root", "123456");
After you end the operation of the database, mysql_connect () is automatically disconnected, or you can use Mysql_close () explicitly to disconnect the connection.
Mysql_pconnect () establishes a persistent connection, and once the connection is established, the connection is placed in the connection pool, even if the database operation ends
The connection is not automatically closed, but is left for later use. The function mysql_pconnect () can not be closed even if the mysql_close () function is used.
The connection.
After you complete the database operation, you should close the connection. But shutting down is not required because PHP has garbage collection and will automatically do the unused connections
Processing. Of course, you can close the connection explicitly, and a resource ID is required to close the connection, and if not specified, the most recently opened connection is closed by default.
Mysql_close (Resource identification number);
3. Select Database
Select Database mysql_select_db (database name, resource identification number);
4, Query the database
Functions that perform query operations are mysql_query () and Mysql_db_query (). Where the function mysql_query () executes an SQL statement directly,
The function mysql_db_query () can execute the SQL statement on the specified database.
mysql_query (SQL statement, resource identification number):
If the SQL statement is a query statement such as SELECT, Show, Expllain, describe, a resource ID number is returned when execution succeeds and false on failure
Returns true if the SQL statement is another statement (INSERT, UPDATE, Delete, and so on), false on failure.
Mysql_db_query (database name, SQL statement, resource identification number) function Ditto, this sentence is equivalent to the combination of mysql|_slect_db () and mysql_query ().
5. Get and display data
Mysql_fetch_row (Resource ID) returns the current record row in the query result set as an array and moves the current row pointer down one row in the result set after the call
Mysql_fetch_array (Resource ID) returns the current record row in the query result set as an array, and moves the current row in the result set down one line after the call
Note:mysql_fetch_row () returns an array of results that can only be accessed using a digital subscript, mysql_fetch_array () returns an array of results that can use an array subscript,
You can also use the field name for access, but mysql_fetch_row () can get the fastest execution speed
MYSQL_FETCH_ASSOC (Resource ID) returns the current record row in the query result set as an associative array and moves the current row pointer down one row in the result set after the call
Mysql_fetch_object (Resource identification number) returns the current record row in the query result set as an object, and moves the current row pointer down one row after the whine is used
Mysql_result (resource ID, line number, field) fields can use a numeric index, or you can use a field name. Digital index subscript starting from 0
This function returns the value of the specified field for the specified record row
Mysql_num_rows (Resource identification number) returns the number of rows of records that match the query criteria
Mysql_field_seek (Resource identification number, positioned line number) to navigate to the row to query
The Mysql_fetch_length (Resource identification number) is returned as an array of numeric indices, and each array element value corresponds to the number of bytes in one field
6, Data deletion and modification and related operations
Use mysql_query () to complete data additions and deletions and change operations
int Mysql_affected_rows (Resource identification number) returns the number of records affected by INSERT, UPDATE, and delete
Mysql_num_rows () is valid only for SELECT statements