PHP quick growth _ php instance

Source: Internet
Author: User
Tags switch loop
This article is a simple and comprehensive introduction to the relevant knowledge of php. php is very simple to get started. A Brief Introduction to PHP syntax

1. embedding method:

PHP can be <? Php or <?, End symbol?>, Of course, you can also specify it yourself.

2. Reference a 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:

Program code

The Code is as follows:


<? Php
Echo "This is the first example. "; // Note the C ++ syntax in this example
/* This example uses multiple rows
Annotation Method */
Echo "this is the second example. ";
Echo "is the third example. "; # This example uses UNIX Shell syntax annotations
?>

4. Variable type:

The Code is as follows:


$ Mystring = "I Am a string ";
$ NewLine = "NewLine ";
$ 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:

Mathematical operations: 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 &

Program code

The Code is as follows:


<?
$ 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 the <% = variable %> in ASP, which can be used in PHP. <? = Variable? >.

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)

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.

Program code

The Code is as follows:


<? Php
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.

Program code

The Code is as follows:


<? Php
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.

Program code

The Code is as follows:


<? Php
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.

Program code

The Code is as follows:


<? Php
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.The 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.

Program code

The Code is as follows:


<? Php
For ($ I = 1; $ I <= 10; $ I ++ ){
Echo "This is the first loop". $ I ."
";
}
?>

3. switch LoopGenerally, compound condition judgment is processed. Each subcondition 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.

Program code

The Code is as follows:


<? Php
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.

Objective: To learn how to build a database

In ASP, if it is an ACCESS database, you can directly open ACCESS to edit the MDB file. If it is an SQL server, you can open the Enterprise Manager to edit the SQL SERVER database, but in PHP, the command line editing of my SQL may be very troublesome for beginners. It doesn't matter. You can download and install PHPMYADMIN, and you can rely on it to create and edit a database later.

The following describes how to use it.
After entering phpmyadmin, we first need to create a database, Language (*) Here select Simplified Chinese, then create a new database on the left here fill in the Database Name, 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

An important feature 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.

Objective: To learn how to connect to a 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.

Objective: to 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 returned class information. 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:

Program code

The Code is as follows:


<?
$ 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

Program code

The Code is as follows:


<%
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.

Objective: 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.
We can comment out mysql_query ($ exec); the statement uses echo $ exec; instead of 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.

Objective: To learn how to use a SESSION

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

Program code

The Code is as follows:







This is the case when processing files.

Program code

The Code is as follows:


<?
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:

Program code

The Code is as follows:


<?
$ 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. asp.

Program code

The Code is as follows:


<?
Session_start ();
If ($ _ SESSION ['adminname'] = ')
{
Echo "script" alert ('Please Login First '); location. href = 'login. php'; script ";
}
?>

Objective: To create a paging display

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.

The Code is as follows:


$ 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.

The Code is as follows:


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:

Program code

The Code is as follows:


FirstPage
"> PrevPage
"> NextPage
"> LastPage

This is a general idea. You can think about how to optimize it?

Objective: To learn more

Because I learned ASP first, I will find many places to adapt when I do PHP again.

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 whether the addition is successful can be verified directly in the data base, and 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.

Objective: To Learn How 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:

The Code is as follows:


$ 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 Reply-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.

Is it possible to learn php soon? I hope my friends will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.