PHP getting started

Source: Internet
Author: User
Tags switch loop
The following is a brief introduction to PHP syntax. 1. Embedding Method: Like ASP %. Can PHP be? Php or ?, What is the end symbol ?, Of course, you can also specify it yourself. 2. File Reference: There are two methods to reference a file: require and include. How to Use require, such as require (MyRequireF

The following is a brief introduction to PHP syntax. 1. Embedding Method: Like ASP %. Can PHP be? Php or? , What is the end symbol? Of course, you can also specify it yourself. 2. File Reference: There are two methods to reference a file: require and include. How to Use require, such as require (MyRequireF

Ten days to learn PHP

The following describes the PHP syntax.

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:

  
  

4. Variable type:

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

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 &

  
  

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 today. Let's talk about process control tomorrow.

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.

  

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.

 ";}?>


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: Modify the preceding example to a more complete process. Because else only executes one line of commands, no braces are added.

 
 ";}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.

 $ B) {echo "a is larger than B";} elseif ($ a = $ B) {echo "a is equal to 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 a judgment condition, which is usually determined by using a logical operator number (logicaloperators. 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.

  
 ";}?>

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.

  

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.

Let's talk about database usage today.

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 (stringdatabase_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.

Let's talk about this today. Let's talk about database reading tomorrow.

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:

 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,1do while not rs.eofresponse.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. Today we will talk about how to add, delete, and modify data.

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 tablenamewhere ...";

Modify: $ exec = "update tablename setitem1 = '". $ _ 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.

Let's talk about it today. You can go DOWN a reference manual for SQL statements and study it again. Continue to talk about the SESSION tomorrow

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

 
 


This is the case when processing files.

 password==$password)    {     $_SESSION['adminname']=$username;     header("location:index.php");    }    else    {      echo"《script》alert('Password CheckError!');location.href='login.php';《script》";    }  }  else  {  echo"《script》alert('Username CheckError!');location.href='login.php';《script》";  }  }else{echo "《script》alert('Database ConnectionError!');location.href='login.php';《script》";}?>


Conn. php is like this:

  

Because $ _ SESSION ['adminname'] = $ username; we can write a file to verify whether the statement is logged on: checkadmin. asp.

  

Let's talk about how to create a page tomorrow.

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.

$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 the page starts from 0,-1} is required}

In this way, $ exec can be written in this way.

$ Exec = "select * fromtablename limit". ($ page * 10). ", 10 ";

// One page is 10 records

What we need to do at last is several connections:

FirstPage">PrevPage">NextPage">LastPage


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

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

Now, let's talk about uploading files and sending emails in PHP tomorrow.

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:

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

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.