Recommended:php mysql
This article records the process of learning PHP and mySQL. I briefly learned these two languages on the Internet before, and wrote PHP myself, which can connect to mySQL normally and insert data. But I always feel that it is still unclear. So I borrowed O'REILLY's PHP, MySQL, JavaScript, & CSS. I hope that I can clarify my programming ideas and learn more clearly, which will help me write projects in the future.
First of all, let’s take a look at what these languages are mainly responsible for. PHP is responsible for the main work on the server, MySQL is responsible for all data, and CSS and JavaScript manage the display of web pages. However, JavaScript can also communicate with PHP whenever it needs to update some information on the server or on the page.
PHP is a relatively loose language. That is, its variable type does not need to be declared before use. Numbers within strings can be automatically converted to numeric types.
PHP uses ‘$’ to define variables. For example: $ my_counter = 1;
Use whitespace to make the code cleaner and clearer, and easier to understand when you look back. It also helps other developers maintain your code. If you need to declare a numeric variable, whether it is an Int type or a Float type, you can declare it directly.
For example: $ count = 17; $ count = 17.5;
1. Start with a letter or '_' (underscore);
2. It can only contain a-z, A-Z, 0-9 and '_' (underscore);
3. It cannot contain spaces. If it must contain two words, it must use '_' (underscore) ) to separate;
4. It is case-sensitive, $High_Score and $high_score are different variables.
1. You don’t need to use ($) to declare a constant. It usually starts with a character or an underscore
2. You can only use the define method. Assign a value to the constant define ('TIREPRICE', 100);
3. This value cannot be changed in the script.
4. Unlike variables, constants are automatically global throughout the entire script.
5. Try not to use (_) both before and after to name variables.
To set a constant, use the define() function - it uses three parameters:
The first parameter defines the name of the constant, the second parameter defines the constant value, and the optional third The parameter specifies whether the constant name is case-insensitive. The default is false.
Short style short style: $tireqty is very convenient, but you need to set the register_globals configuration option to on. Due to security reasons, this option is off by default.
Medium style: $_POST[ ' tireqty ' ] Recommended
Long style $HTTP_POST_VARS[ ' tireqty' ] has been deprecated
We usually recommend Use medium style to declare variables. If you create a short style and then assign the medium style to it, there is no security issue and it will be easier to use. $tireqty = $_POST [ 'tireqty' ] ;
Single quotes will not treat strings starting with $ in the text as variables. If you want to treat it as a variable, you need to use double quotes. If you want to use single quotes within the string, you cannot use them directly. This is the same as JavaScript. The escape character "\" is needed to solve the single quote problem. In addition, \t, \n, \r are only valid within double quotes.
PHP also provides the operator "<<<" for multi-line arrays. The advantage is that it is convenient to output large sections of HTML, does not require escaping, and can quote variables. "<<<" is followed by any name you like (custom delimiter) and ends with this. Entering the text between them will not be displayed. The variables inside will be available. If the variables are not required, you can use "." to connect them. At this time, it will not be interpreted as a variable, but will be output normally.
When using (<<<), one thing to note is that the end of the identifier string (such as: END) needs to occupy an exclusive line, and no content including spaces is allowed before and after, otherwise this The PHP file is equivalent to useless.
These two commands are very similar. Butprintis a function method that requires a parameter, butechois a structure of thePHPlanguage. In ordinary text output,echois slightly faster thanprintbecause it is not a function and does not need to set a return value. At the same time, becauseechois not a function, it cannot be used for a large number of complex expressions, butprintcan.
Function is used to distinguish codes that implement different special functions. For example, this code prints three lines of text, but if I want to print more than a dozen, I need to copy and paste these codes constantly, which undoubtedly makes the code more complex and larger. But with function, you only need to use the function once to print more than a dozen times. It makes the code cleaner and more readable. Functions are declared in the same way as JavaScript.
For example:
function longdate($timestamp){
return date("l F jS Y",$timestamp);
}
PHP Variable Scope
In the PHP language, you can determine the scope of the variable, for example, only Used within a function, or globally scoped, any scope can be used.
Local Variables (local variables)means that variables are created and are only allowed to be called in functions. It is a zero-time storage and ceases to exist once the function is completed.
Global Variables (global variables)Sometimes we also need global variables, because you want all your code to be able to call it. When we need to declare a global variable, we need to use the keywordglobal. It is not recommended to use global variables. You can use them when there is no other way. Because the general program is broken into multiple small parts, such data problems are also small problems that are easy to maintain. But if the program with thousands of lines of code finds that there is a problem with your global variables. Then it will take a lot of energy and time to maintain it. At the same time, it is recommended that when naming global variables, it is best to use uppercase letters.
Static Variables (static variables)When you use a variable and hope that it can only be called in a function, but you also hope that it can be used again the next time this function is used, the value will not is restored to its original value. At this time we need to use static variables. At the same time, it should be noted that static variables cannot be assigned a calculation formula or function, and must be assigned an actual value.
For example:
static $int = 0; //Allowed
static $int = 1 2; //Disallowed (will produce a Parse error)
static $int = sqrt(144); //Disallowed
Superglobal Variables (Super global variables) Many predefined variables in PHP are "super global", which means This means they are available in all scopes of a script.
These superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
These super global variables Names use underscores and capital letters, so duplication should be avoided when naming to cause confusion in the program.
Boolean expression, it is worth noting that in PHP, the value of TRUE is "1", while the value of FALSE is NULL, Or a null value. Because in some languages FALSE is defined as 0 or -1.
In addition, PHP will judge the variable type according to the literal value (literals) understanding.
For example:
$myname = "Brian";
$myage = 37;
echo "a: " . 73 . "
"; //Numeric literalecho "b: " . "Hello" . "
"; //String literalecho "c : " . FALSE . "
"; //Constant literalecho "d: " . $myname . "
"; //Variable string literalecho "e: " . $myage . "
"; //Variable numeric literalThe result is:
a: 73 b: Hello c: d : Brian e: 37
PHP operators (operators)
PHP provides a large number of useful operators, such as calculations, string and logical operations symbol. The "." operator is used to concatenate strings.
PHP logical operator (logical)
The return value of "or" is a Boolean value. Returns true if at least one of $x and $y is true.
"xor"The return value is a Boolean value. The condition is either A or B. If A, it returns True, if it is B, it also returns True. But if it is A and B, it returns False. If it is neither A nor B, it returns False. Therefore, if one and only one of the conditions is true, then true is returned.
PHP Associativity Operator (associativity)
This type of operator is calculated from right to left.
Operator
NEW Create a new object
! Logical NOT
~ Bitwise NOT
-- Increment and decrement
- Unary plus and negation
(int) Cast to an integer $c = (int) ($a / $b);
(double) Cast to a float
(string) Cast to a string
(array) Cast to an array
(object) Cast to an object
@ Inhibit error reporting
@是为了抑制错误显示,让用户看不到,提升用户体验。注意:只是抑制错误,但是错误还是存在的。
= Assignment
PHP条件表达式(Conditionals)
条件表达式是动态页面的核心,它能够简单地根据不同的条件创造出不同的页面结果。有三种表达方法:if,switch和?(三目运算符)。这个和JavaScript都是一样的。
PHP循环(Looping)
能快速地周而复始地工作直到事情发生为止。循环方式有:while,do……while和for。
PHP的函数与对象
函数的好处:
1. 简洁
2. 减少语法和其他编写程序的错误
3. 减少程序文件的加载时间
4. 同时减少执行时间,因为每一个函数都仅仅被解析一次,无论它将被调用多少次。
5. 函数接受参数,这样能够被普遍使用,也同时能被特殊的情况使用。
PHP有上百种已经编写好的函数,使它成为一个丰富的语言。
Include和require
require()的性能与include()相类似,都是包括并运行指定文件。不同之处在于:对include()语句来说,在执行文件时每次都要进行读取和评估;而对于require()来说,文件只处理一次。这就意味着如果可能执行多次的代码,则使用require()效率比较高。另外一方面,如果每次执行代码时是读取不同的文件,或者有通过一组文件迭代的循环,就使用include()语句。
The usage method ofrequireis as follows:require("myfile.php"). This statement is usually placed at the front of the PHP script program. Before the PHP program is executed, it will first read the file introduced by therequire()statement, making it a part of the PHP script file.includeis used in the same way asrequire, such as:include("myfile.php"), and this statement is generally placed in the processing section of the process control. The PHP script file only reads the files it contains when it reads theinclude()statement. In this way, the process of program execution can be simplified.
includeLoad when usedrequireLoad at the beginning
include/require_onceThe suffix indicates Loaded does not load
The PHP system has a pseudo-compilation process when loading a PHP program, which can speed up the running speed of the program. However, theincludedocument is still interpreted and executed. There is an error in the fileinclude, and the main program continues to execute. There is an error in the filerequire, and the main program is stopped. Therefore, if the error in the included file has little impact on the system ( If the page file is bounded, useinclude, otherwise userequire.
require()andinclude()statements are language structures, not real functions. They can be like other language structures in php, for example, echo() can Use echo("ab") form, or echo "abc" form to output the string abc.require()andinclude()statements can also add parameters directly without parentheses. The
include_once()andrequire_once()statements also include running the specified file during script execution. This behavior is similar to theinclude()statement andrequire(), and the usage method is the same. The only difference is that if the code in the file is already included, it will not be included again. These two statements should be used when the same file may be included more than once during script execution to ensure that it is only included once to avoid problems such as function redefinition and variable reassignment.
function_exists("function name")is to determine whether this function is valid.
Object Object
Object-oriented programming OOP (object-oriented programming OOP) takes functions to a new level. When some methods are to be reused, you can consider putting these methods and data into objects. Think about a social networking site. It has many parts. One component is to manage all user functions. For example, allowing new users to register and existing users to change their information. Generally, we will create some functions to manage these and request the MySQL database to log all users. After we know the object, we can create an object named User and put all the data and methods into this object. So whenever we need to manipulate a user's data, we can simply create an object related to the User class. The data in an object are called properties, and the functions in an object are called methods. If you find that you need a class outside the class, this class is very similar to the User class, but has some differences, then we need to inherit the User class. Then the original User class is called the parent class (superclass), and the new class is called the subclass (subclass/derived class).
Declaring a Class
Before using an object, you must define a class with the keywordclass. Defining a class consists of the class name (which is case-sensitive), the class's attributes, and the class's methods. You can use '->' to assign values to variables/properties. This is a variable that does not need to be declared with $.
Constructors (Constructors)
A method with parameters in a class and the same name as the class is called a constructor. Many people now use __construct to name the constructor. When the object is no longer needed, the destructor needs to be called to release the memory occupied by the object. But the destructor does not need to be designed because the system will automatically release specific memory. Unless you use dynamic memory, then you have to design a destructor to tell the system which memory to release.
Declaring a method (Methods)
Declaring a method is very similar to declaring a function, but there are still some differences. For example, the name of a method begins with two underscores (__). $this refers to the current object and returns the property values of this object.
Static methods (static methods)
In PHP programming, the static keyword declares that a property or method is related to the class, not to a certain part of the class. Related to a specific instance, therefore, such attributes or methods are also called "class attributes" or "class methods"
If access control permissions allow, you do not need to create an object of this class and directly use the class name plus two Called by colon "::".
User::pwd_string();
class User
{
static function pwd_string()
{
echo "Please enter your password";
}
}
?>
Declaring Properties
Declaring properties does not have to be in the class In, there are no attributes and methods in the class but they are still legal. However, in order to help yourself and others better understand and maintain the code, it is still recommended to put the declaration of attributes into the class.
$object1 = new User();
$object1->name = "Alice";
echo $object1->name;
class User {}
?>
Declaring a constant
To define a constant, you need to addconstbefore the constant name. Constant names generally use uppercase letters to make them stand out. When a constant/variable uses the keywordsselfandwith two colons (::), itcan be directly referenced.
Property and Method Scope
PHP provides 3 keywords to control the scope of properties and methods. 1. public - These properties are declared using thevarandpublickeywords. Public and var are interchangeable, although this is frowned upon. When external code wants to call this property, or the extended class needs to inherit it, we should use public to declare it.
2. protected - These properties and methods can only be referenced by methods in the object and any subclasses. When we don't want to be called by external code, but the extended class wants to inherit it, we can use protected to declare it. 3. private - these members can only be referenced by the same class, and subclasses cannot reference them. When we do not want these members to be called by any external code methods or classes, we should use private to declare them.Static properties and methods
Static methods can be called directly, but properties cannot. When calling properties, you can use the keyword self and a double colon to call static properties inside the class.Inheritance
Any class can be inherited. Reduce the duplication of code, just change a small part and adjust different places. Use the keywordextendsto declare extensions.
PHP array (Arrays)is_array($array_name)Returns a Boolean value to determine whether the array is valid.
sort($array_name, SORT_NUMERIC/STRING)Sort numbers and strings from small to large.
rsort($array_name, SORT_NUMERIC/STRING)Sort from large to small by numbers and strings.
shuffle($array_name)Shuffle the array and sort it randomly.
explode(' ',"string")This is a very useful method. It will separate the input string into individual elements according to the requirements and then put them into an array. The first parameter is what to split by, and the second is the string to put in.
extract()This method can easily convert the array into the form of key-value pairs. Often used for$_POSTand$_GET.
extract(array,extract_rules,prefix)There are three parameters,
The first array is required. Specifies the input to use. The second extract_rules is optional. The extract() function will check whether each key name is a legal variable name, and also checks whether it conflicts with the variable name in the symbol table. The handling of illegal, numeric, and conflicting key names will be determined based on this parameter. Can be one of the following values: Possible values:
- EXTR_OVERWRITE - Default. If there is a conflict, existing variables are overwritten.
- EXTR_SKIP - Do not overwrite existing variables if there is a conflict. (Ignore elements with the same name in the array)
- EXTR_PREFIX_SAME - If there is a conflict, prefix the variable name with prefix. As of PHP 4.0.5, this also includes handling of numeric indexes.
- EXTR_PREFIX_ALL - Prefix all variable names with prefix (third parameter).
- EXTR_PREFIX_INVALID - Prefix only illegal or numeric variable names with prefix. This tag is newly added in PHP 4.0.5.
- EXTR_IF_EXISTS - Overwrite the values of variables with the same name only if they already exist in the current symbol table. Others are not processed. It can be used when a set of legal variables has been defined, and then you want to overwrite these variables by extracting values from an array such as $_REQUEST. This tag is newly added in PHP 4.2.0.
- EXTR_PREFIX_IF_EXISTS - Only when a variable with the same name already exists in the current symbol table, a variable name with a prefix is created, and nothing else is processed. This tag is newly added in PHP 4.2.0.
EXTR_REFS - Extract variables as references. This is a strong indication that the imported variable still references the value of the var_array parameter. This flag can be used alone or in combination with any other flag using OR in extract_type. This tag is newly added in PHP 4.3.0.
The third parameter, prefix is optional. Note that prefix is only required if the value of extract_type is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the result after appending the prefix is not a legal variable name, it will not be imported into the symbol table. An underscore is automatically added between the prefix and the array key name.
The code is as follows:
$a = 'Original';
$my_array = array("a" = > "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
Output:
$a = Cat;
$b = Dog;
$c = Horse
Use all parameters:
The code is as follows:
< ;?php
$a = 'Original';
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array, EXTR_PREFIX_SAME, 'dup');
echo "\$a = $a; \$b = $b; \$ c = $c; \$dup_a = $dup_a;";
?>
Output:
$a = Original;
$b = Dog;
$c = Horse;
$dup_a = Cat;
In action.php, just use the extract() function to $_POST global data Unlock:
action.php
The code is as follows:
extract($_POST); //Equivalent to $username = $_POST['username']; //$password = $_POST['password'];
?>
##compact(var1,var2 ...)The function creates an array consisting of the variables taken by the parameters. If there is an array in the parameter, the value of the variable in the array will also be obtained.
The array returned by this function is an associative array, the key name is the parameter of the function, and the key value is the value of the variable in the parameter. The behavior performed by this function is exactly the opposite ofextract().
Example 1 Use a string that does not match the variable, and an array of variable names:$firstname = "Bill"; $lastname = "Gates"; $age = "60"; $name = array("firstname", "lastname"); $result =compact($name, "location", "age"); print_r($result); ?>Output result: Array ([firstname] => Bill [lastname] => Gates [age] => 60 ) Other related methods:current()- Returns the value of the current element in the array
end()- Points the internal pointer to the last element in the array and outputs it
next()- Point the internal pointer to the next element in the array and output
prev()- Point the internal pointer to the array The previous element in and output
each()- Returns the key name and key value of the current element, and moves the internal pointer forward
printf(arg1,arg2,agr)The function outputs a formatted string.arg1,arg2,argparameters will be inserted into the main string at the percent sign (%) symbol. This function is executed step by step. At the first % sign, insertarg1, at the second % sign, insertarg2, and so on.
Parameters Specifies a string and how to format variables within it. # Positive numbers) 2) E - Use uppercase scientific notation (e.g. 1.2E 2) %u - a decimal number without a sign (greater than or equal to 0) %f - floating point number (local setting )%f -floating point number (non -local settings)
%G -shorter%e and%f
##zhi -shorter%e and%f because Capital letters) Must be placed between % and a letter (e.g. %.2f):(preceded with or - to define the signification of a number. By default, only Negative numbers are marked, positive numbers are not marked)
Default is space . It must be used with a width specifier.)
Value)
[0-9] (Specifies the number of decimal places or the maximum string length) If multiple above format values are used, they must be used in the order above and cannot be disrupted.arg1Specifies the parameters to be inserted into theformatstring at the first % symbol.
arg2Specifies the parameter to be inserted at the second % symbol in theformatstring.
arg. Specifies the parameters to be inserted into theformatstring at the third, fourth, etc. % symbols.
PHP printf() function
Appendices:
syntax
#manipulate /məˈnɪpjuleɪt/ col DisagreeThe above is the detailed content of Record the bitter history of learning PHP and mySQL. For more information, please follow other related articles on the PHP Chinese website!