PHP syntax entry (Yufeng sorting)

Source: Internet
Author: User
1. 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 stored in PHPProgramBefore 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 (myshortdefile. 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.

2. Variable type:

 

$ Mystring = I am a string;
$ Newline = line feed \ 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.

3. Connect to the 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.

4. Read data

(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. "<br> ";
}
?>
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") & "<br>"
Rs. movenext
Loop
%>
Of course, you need to connect to the database first. Generally, we require_once ('conn. php'), and in conn. php, we talked about connecting to the databaseCode.

5. 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 a <input name = "Item1" type = "text" id = "Item1">
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.

7. Session usage

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
<Table width = "100%" Height = "100%" border = "0" align = "center" cellpadding = "0" cellspacing = "0">
<Tr>
<Form action = "checklogin. PHP "method =" Post "> <TD align =" center "valign =" Middle "> <Table width =" 400 "border =" 0 "cellpadding =" 5 "cellspacing = "1" class = "tablebg">


administrators login



username






Password













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. asp.
<?
Session_start ();
If ($ _ session ['adminname'] = '')
{
Echo "<SCRIPT> alert ('Please login first '); location. href = 'login. php'; </SCRIPT> ";
}
?>

8. 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:
<A href = "XXX. php? Page = 0 "> firstpage </a>
<A href = "XXX. php? Page = <? = ($ Page-1)?> "> Prevpage </a>
<A href = "XXX. php? Page = <? = ($ Page 1)?> "> Nextpage </a>
<A href = "XXX. php? Page = <? = Ceil ($ num/10)-1?> "> Lastpage </a>

10. Use PHP to upload files and send emails

Enctype = "multipart/form-Data" must be added to the file upload form"
And <input type = "file" name = "file">
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.

This is a general idea. You can think about how to optimize it? Today, let's talk about some important issues tomorrow.

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.