I hope you can understand this. this is just about how to get started and better understand PHP! You can also master basic PHP knowledge! The PHP language is profound and profound! It's not a day or two! It takes a long time to learn! Next, let's take you on the road to getting started with PHP.
Note:
I am currently using Apache web server and my SQL as WEB server and database, in the php-4.3.3 environment to do the program. Of course, it is essential to simply build and access the PHPMYADMIN database.
Here you need to understand the basic HTML knowledge! No basic HTML knowledge! You can search baidu or GOOGLE! Very easy! I will not talk about it here.
Let's get started! Let's take PHP entry as an apple! Eat him in one bite!
No worries! Started
Eat apple 1
1. embedding method:
PHP, similar to ASP, can be Of course, you can also specify it yourself.
2. Reference File:
There are two methods to reference files: require and include.
The use of require is as follows: require ("MyRequireFile. php ");. This function is usually placed at the beginning of the PHP program. before the PHP program is executed, it will first read the file specified by require to make it a part of the PHP program webpage. This method can also be used to introduce common functions into webpages.
Include usage methods such as include ("mydomaindefile. php ");. This function is generally placed in the process of process control. The PHP program webpage reads the include file. In this way, you can simplify the process during program execution.
3. annotation method:
Echo "this is the first example. \ N "; // In this example, the C ++ syntax annotation (PHP annotation is similar to C !)
/* This example uses multiple rows
Annotation method */
Echo "this is the second example. \ N ";
Echo "is the third example. \ N "; # This example uses the UNIX Shell syntax to annotate
?>
4. variable type:
$ Mystring = "I am a string ";
$ NewLine = "NewLine \ n ";
$ Int1 = 38;
$ Float1 = 1.732;
$ Float2 = 1.4E + 2;
$ MyArray1 = array ("child", "ugly", "Yin", "Mao ");
Two problems are raised here. First, the PHP variable starts with $, and the second PHP statement ends with;, which may be unsuitable by ASP programmers. These two omissions are also the cause of many program errors.
5. operator number:
Counting ** invalid words blocked:
Symbolic meaning
+ Addition operation
-Subtraction
* Multiplication
/Division
% Obtain the remainder
++ Accumulate
-- Decrease
String operation:
There is only one operator number, which is an English ending. It can be used to connect strings and convert them into new merged strings. Similar &
$ A = "PHP 4 ";
$ B = "powerful ";
Echo $ a. $ B;
?>
Two problems are also raised here. the output statement in PHP is echo, and the second is similar to <% = variable %> in ASP. PHP can also .
Logical operation:
Symbolic meaning
<Less
> Greater
<= Less than or equal
> = Greater than or equal
= Equal
! = Not equal
& And (And)
And (And)
Or (Or)
Or (Or)
Xor exclusive or (Xor)
! No (Not)
Let's talk about process control.
Objective: to master php process control
1. if... else loop has three structures
The first is to use the if condition as a simple judgment. It is interpreted as "how to deal with something ". Syntax:
If (expr) {statement}
Expr is the judgment condition, which is usually determined by the logical operator number. Statement is the execution part of the program that meets the conditions. if the program has only one line, you can omit braces {}.
Example: braces are omitted in this example.
If ($ state = 1) echo "haha ";
?>
It is important to note that, to determine whether the equality is equal to = rather than =, ASP programmers may often make this mistake, = is a value assignment.
Example: the execution part of this example has three rows and the braces cannot be omitted.
If ($ state = 1 ){
Echo "haha;
Echo"
";
}
?>
In addition to the if clause, the first two conditions of else can be interpreted as "what to do if something happens, otherwise how to solve it ". Syntax:
If (expr) {statement1} else {statement2} example: the above example is modified to a more complete processing. Because else only executes one line of commands, no braces are added.
If ($ state = 1 ){
Echo "haha ";
Echo"
";
}
Else {
Echo "haha ";
Echo"
";
}
?>
The third type is the recursive if... else loop, which is usually used for multiple decision making decisions. It combines several if... else values for processing.
Let's look at the example below.
If ($ a> $ B ){
Echo "a is larger than B ";
} Elseif ($ a ==$ B ){
Echo "a equals B ";
} Else {
Echo "a is smaller than B ";
}
?>
In the above example, we only use the layer-2 if .. else loop to compare the two variables a and B. Actually, we need to use this recursion if .. please be careful when using else loops, because too many layers of loops may cause problems in the design logic, or if you leave less braces, the program may encounter inexplicable problems.
2. there is only one for loop without any change. Its syntax is as follows:
For (expr1; expr2; expr3) {statement}
Expr1 is the initial value of the condition. Expr2 is the condition for judgment. it is usually determined by a logical operator number (logical operators. Expr3 is the part to be executed after statement is executed. it is used to change the condition for the next loop judgment, such as adding one. Statement is the execution part of the program that meets the conditions. if the program has only one line, you can omit braces {}.
The following is an example of using for loop writing.
For ($ I = 1; $ I <= 10; $ I ++ ){
Echo "this is the first loop". $ I ."
";
}
?>
3. switch loop, usually processing compound condition judgment. each sub-condition is part of the case instruction. In practice, if many similar if commands are used, they can be combined into a switch loop.
Syntax:
Switch (expr) {case expr1: statement1; break; case expr2: statement2; break; default: statementN; break ;}
The expr condition, usually the variable name. The exprN after case usually represents the variable value. The part that meets the condition after the colon. Note that you must use the break to skip the cycle.
Switch (date ("D ")){
Case "Mon ":
Echo "today Monday ";
Break;
Case "Tue ":
Echo "Tuesday ";
Break;
Case "Wed ":
Echo "Wednesday ";
Break;
Case "Thu ":
Echo "Thursday ";
Break;
Case "Fri ":
Echo "Today's Friday ";
Break;
Default:
Echo "today's holiday ";
Break;
}
?>
Here, you need to note break; do not miss it, default. it is acceptable to omit it.
Obviously, it is very troublesome to use the if loop in the above example. Of course, in the design, the conditions with the highest probability should be placed at the beginning, and the minimum conditions should be placed at the end, which can increase the execution efficiency of the program. In the previous example, because the probability of occurrence is the same every day, you do not need to pay attention to the order of conditions.
Learn to build databases
In PHP, the command line editing of my SQL may be very troublesome for beginners. it doesn't matter. you need to download a PHPMYADMIN and install it. you can establish a database for editing later.
The following describes how to use it.
After entering phpmyadmin, we first need to create a database,
Select simplified Chinese Language (*), create a new database on the left, enter the database name here, and click create.
Select the created database from the drop-down list on the left. In the following
Create a new table in the database shop:
Name:
Number of fields:
Enter the table name and the approximate number of fields you think (it doesn't matter if it is not enough or more, you can add it later or use the default value), and click execute.
Then you can create a table.
The first column is the field name, and the second column selects the field type:
We usually use the following:
1) VARCHAR, text type
2) INT, integer type
3) FLOAT, floating point type
4) DATE, DATE type
5) You may ask, where is the automatically added ID? You only need to select the INT type, and select auto_increment in the additional section below.
After creating a table, you can see the table you created on the left. after clicking it, you can:
1) view and modify the table structure by structure on the right
2) click browse on the right: view the data in the table
3) press SQL on the right to run the SQL statement.
4) insert to the right: insert a row of records
5) clear by right: delete all records in the table
6) delete the table on the right: delete the table
Another important function is import and export. when the program and database are ready on the local machine, a local image is required on the server. if asp access is simple, directly upload the MDB file. if it is an SQL SERVER, you can connect to the remote SERVER for import. In my SQL, you can export all the SQL statements to PHPMYADMIN on the remote server. after creating the database, press SQL and paste all the SQL statements generated at the current level that you just copied.
Learn to connect to the database
PHP is simply a function library. rich functions make some parts of PHP quite simple. We recommend that you use a PHP function manual.
Let me briefly talk about connecting to the MYSQL database.
1. mysql_connect
Open the MySQL server connection.
Syntax: int mysql_connect (string [hostname] [: port], string [username], string [password]); return value: integer
This function establishes a connection with the MySQL server. All parameters can be omitted. When you use this function without adding any parameters, the default value of the hostname parameter is localhost, the default value of the username parameter is the owner of the PHP route execution, and the parameter password is a null string (that is, no password ). The hostname parameter can be followed by a colon and a port number, indicating which port is used to connect to MySQL. Of course, when using the database, you can use mysql_close () to turn off the connection earlier to save resources.
2. mysql_select_db
Select a database.
Syntax: int mysql_select_db (string database_name, int [link_identifier]); return value: integer
This function selects a database on the MySQL server for subsequent data query job (query) processing. True is returned for success, and false is returned for failure.
The simplest example is:
$ Conn = mysql_connect ("127.0.0.1 ","","");
Mysql_select_db ("shop ");
Connect to my SQL database and open the SHOP database. In practical applications, we should strengthen the judgment of point errors.
Learn to read data
Let's first look at two functions:
1. mysql_query
Returns a query string. Syntax: int mysql_query (string query, int [link_identifier]); return value: integer
This function sends a query string for MySQL to perform related processing or execution. If the link_identifier parameter is not specified, the program automatically searches for the recently opened ID. If the query string is UPDATE, INSERT, or DELETE, the return value may be true or false. if the query string is SELECT, a new ID value is returned. if the return value is false, the query string is incorrect, instead of running successfully but without returning values.
2. mysql_fetch_object returns class data. Syntax: object mysql_fetch_object (int result, int [result_typ]); return value: Class
This function is used to split the query result into class variables. If the result contains no data, false is returned.
Let's look at a simple example:
$ Exec = "select * from user ";
$ Result = mysql_query ($ exec );
While ($ rs = mysql_fetch_object ($ result ))
{
Echo "username:". $ rs-> username ."
";
}
?>
Of course, the table user has a username field, which is similar
<%
Exec = "select * from user"
Set rs = server. createobject ("adodb. recordset ")
Rs. open exec, conn, 1, 1
Do while not rs. eof
Response. write "username:" & rs ("username ")&"
"
Rs. movenext
Loop
%>
Of course, you need to connect to the database first. generally, we require_once ('Conn. php'), while conn. php contains the code used to connect to the database.
Two small commands can be used to read data.
Learn to add, delete, and modify data
Mysql_query ($ exec );
This statement can execute all the operations. The difference is that the SQL statement $ exec
Add: $ exec = "insert into tablename (item1, item2) values ('". $ _ POST ['item1']. "',". $ _ POST ['item1']. ")";
Delete: $ exec = "delete from tablename where ...";
Modify: $ exec = "update tablename set item1 = '". $ _ POST ['item1']. "'Where ...";
Let's talk about the transfer of form and php variables. if
If the form is submitted in POST mode, you can use $ _ POST ['item1'] to obtain the variable value for processing the Form File. Similarly, $ _ GET ['item1'] is submitted in GET mode.
Is it easy? But usually $ exec will have a problem, because your SQL statement may be very long, you will miss the. connector, or 'to enclose the character field.
Note mysql_query ($ exec); the statement uses echo $ exec; instead of $ exec to output $ exec to check whether the statement is correct. If you do not notice any error in $ exec, you can copy the SQL statement to phpmyadmin to check its error information. Note that we should not use sensitive strings as field names. otherwise, problems may occur, such as date. Variable naming: Field naming follows a certain rule. sometimes it is good for you. beginners cannot ignore its importance.
Learn how to use Sessions
SESSION has many functions, most of which are the variable transfer between pages on the site.
At the beginning of the page, we want session_start (); to enable SESSION;
Then you can use the SESSION variable. for example, the value to be assigned is $ _ SESSION ['item'] = "item1 "; the value to be obtained is $ item1 = $ _ SESSION ['item'];, which is simple. Here we may use some functions. for example, to determine whether a SESSION variable is null, we can write: empty ($ _ SESSION ['inum']) and return true or false.
Next, let's take a look at the above description to check whether the user name and password are correct.
The login form is as follows: login. php
This is the case when processing files.
Require_once ('Conn. php ');
Session_start ();
$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['password'];
$ Exec = "select * from admin where username = '". $ username ."'";
If ($ result = mysql_query ($ exec ))
{
If ($ rs = mysql_fetch_object ($ result ))
{
If ($ rs-> password = $ password)
{
$ _ SESSION ['adminname'] = $ username;
Header ("location: index. php ");
}
Else
{
Echo "script alert ('password Check Error! '); Location. href = 'login. php'; script ";
}
}
Else
{
Echo "script alert ('username Check Error! '); Location. href = 'login. php'; script ";
}
}
Else
{
Echo "script" alert ('database Connection Error! '); Location. href = 'login. php'; script ";
}
?>
Conn. php is like this:
$ Conn = mysql_connect ("127.0.0.1 ","","");
Mysql_select_db ("shop ");
?>
Because $ _ SESSION ['adminname'] = $ username; we can write a file to verify whether the statement is logged on: checkadmin. php.
Session_start ();
If ($ _ SESSION ['adminname'] = '')
{
Echo "script" alert ('Please Login First '); location. href = 'login. php'; script ";
}
?>
Display by page
The key is to use the limit in the SQL statement to limit the number of records displayed from several to several. We need a variable $ page for recording the current page, and the total number of records $ num
For $ page, if it does not exist, let it = 0. if there is <0, let it ALSO = 0. if it exceeds the total number of pages, let it = the total number of pages.
$ Execc = "select count (*) from tablename ";
$ Resultc = mysql_query ($ execc );
$ Rsc = mysql_fetch_array ($ resultc );
$ Num = $ rsc [0];
In this way, the total number of records can be obtained.
Ceil ($ num/10) if a page contains 10 records, this is the total number of pages.
So you can write it like this.
If (empty ($ _ GET ['Page'])
{
$ Page = 0;
}
Else
{
$ Page = $ _ GET ['Page'];
If ($ page <0) $ page = 0;
If ($ page> = ceil ($ num/10) $ page = ceil ($ num/10)-1; // because page starts from 0, so-1
}
In this way, $ exec can write $ exec = "select * from tablename limit". ($ page * 10). ", 10 ";
// One page is 10 records
What we need to do at last is several connections:
FirstPage
"> PrevPage
"> NextPage
"> LastPage
Notes
1. do not miss a semicolon
2. do not miss the $
3. do not omit session_start () when using SESSION ();
If an error occurs, you can use the following methods:
1. if an error occurs in an SQL statement, comment out and output the SQL statement. Note that you must also annotate the subsequent execution of the SQL statement.
2. if the variable is empty, most of them are not passed in place. check the output variable and check the form id and name.
3. if a database connection error occurs, check whether my SQL is correctly opened and whether the connection statements are omitted.
4. pay attention to indentation and eliminate the error of unpartitioned brackets.
When creating a large website, my idea is to first build a database to determine the role of each field and the relationship between the table. Then design the background interface, starting from adding data, because the addition is successful or not, it can be verified directly in the database, the page for adding and displaying is completed, and finally the combination of the two. In general, the background includes adding, deleting, modifying, and displaying. there is no problem in the background, and there is no major problem in the foreground. The front-end also needs to pay attention to security and fault tolerance, as well as the output format.
Learn to use PHP to upload files and send emails
Enctype = "multipart/form-data" must be added to the file upload form"
And
Let's take a look at the code below:
$ F = & $ HTTP_POST_FILES ['file'];
$ Dest_dir = 'uploads'; // sets the upload directory.
$ Dest = $ dest_dir. '/'. date ("ymd "). "_". $ f ['name']; // Here I set the file name to date plus the file name to avoid duplication.
$ R = move_uploaded_file ($ f ['tmp _ name'], $ dest );
Chmod ($ dest, 0755); // sets the attributes of the uploaded file
The uploaded file name is date ("ymd "). "_". $ f ['name'] can be used later when it is inserted into the database. PHP actually moves the files you uploaded from the temporary directory to the specified directory. Move_uploaded_file ($ f ['tmp _ name'], $ dest );
Mail is simpler. you can use the mail () function.
Mail ("recipient address", "topic", "body", "From: sender \ r \ nReply-to: sender address ");
However, mail () requires the support of the server. in WINDOWS, you also need to configure the SMTP server. Generally, the LINUX space outside will work.
It seems that uploading files and sending emails are much simpler than ASP. you only need to call the function. ASP also needs to use different server components such as FSO and JMAIL.
I have learned PHP and want to tell you that it can take up to ten days to get started with PHP, but it is by no means ten days to be proficient. you also need to study it by yourself and refer to other people's code, understanding is not plagiarism.