10 Days Learn PHP

Source: Internet
Author: User
Tags learn php switch loop
10 days to learn the first day of PHP

With Apache Web server and MY SQL as Web servers and databases under the php-4.3.3 environment do program simple build and access to view database with PHPMYADMIN.

Syntax for PHP:

1. Embedding Method:

PHP can be a , and of course you can specify it yourself.

2. Reference file:

There are two ways to refer to a file: Require and include.

Require use methods such as require ("myrequirefile.php");. This function is usually placed at the front of the PHP program, and before the PHP program executes, it is read into the file specified by require to make it a part of the PHP program's Web page. Commonly used functions, you can also use this method to introduce it into the Web page.

Include usage methods such as include ("myincludefile.php");. This function is usually placed in the processing part of the process control. The PHP Program page reads the include file before it is read in. This way, you can simplify the process when the program executes.

3. Annotation method:

echo "This is the first example. \ n "; This example is a comment for C + + syntax
/* This example uses multiple lines of
Comment Method */
echo "This is the second example. \ n ";
echo "This is the third example. \ n "; # This example uses UNIX Shell syntax annotations
?>

4. Variable type:

$mystring = "I am a string";
$NewLine = "newline \ n";
$int 1 = 38;
$float 1 = 1.732;
$float 2 = 1.4E+2;
$MyArray 1 = Array ("Child", "ugly", "Yin", "Mao");

This leads to two problems: the first PHP variable starts with "$", and the second PHP statement ";" End. These two omissions are also the most procedural errors.

5, Operation symbols:

Mathematical operations:

Symbolic meaning
+ addition operation
-Subtraction operation
* Multiplication operation
/Division Operation
% take remainder
+ + Cumulative
--Diminishing

String Operations:

The operation symbol has only one, is the English period ".". It can concatenate strings together and become merged new strings.

$a = "PHP 4";
$b = "powerful";
echo $a. $b;
?>

Here also leads to two problems, first of all, the output statement in PHP is Echo, the second similar to ASP in the <%= variable%>,php can also 。

Logical operation:
Symbolic meaning
< less than
> Greater than
<= less than or equal to
>= greater than or equal to
= = equals
! = does not equal
&& (and)
And and (and)
|| or (OR)
or or (or)
XOR (XOR)
! No (not)

10 days to learn PHP the next day


Learning Purpose: Mastering the Process Control of PHP

1. If: else loop has three types of structure

The first is to use the IF condition as a mere judgment. Explain how to deal with something if it happens. The syntax is as follows:

if (expr) {statement}

The conditions in which expr is judged are usually determined by the use of logical operation symbols. And statement is a qualifying execution part of the program, if the program has only one row, you can omit the curly brace {}.

Example: This example omits curly braces.

if ($state ==1) echo "haha";
?>

It is particularly important to note that determining whether equality is = = rather than =,asp programmers can often make this error, = is an assignment.

Example: The execution section of this example has three rows and cannot omit curly braces.

if ($state ==1) {
echo "haha;
echo "
" ;
}
?>


The first two is the addition of the IF condition, which can be interpreted as "what to do if something happens or how to resolve it". The syntax is as follows

if (expr) {statement1} else {Statement2} example: the example above is modified to a more complete processing. The else in which there is only one line of instructions, so do not add braces.

if ($state ==1) {
echo "haha";
echo "
";
}
else{
echo "hehe";
echo "
";
}
?>


The third type is recursive if. else loops, often used in a variety of decision-making judgments. It will be a few if. Else to combine the use of processing.

Look directly at the following example

if ($a > $b) {
echo "A is larger than B";
} elseif ($a = = $b) {
echo "a equals B";
} else {
echo "A is smaller than B";
}
?>

The above example uses only two layers of if. else loop, which is used to compare the two variables of a and B. This recursive if is actually to be used. else loop, please be careful to use, because too many layers of the loop is easy to make the logic of the design problems, or less curly braces, etc., will cause the program to appear inexplicable problem.

2, for the loop is only one, no change, its syntax is as follows

for (EXPR1; expr2; expr3) {statement}

Where the EXPR1 is the initial value of the condition. EXPR2 is a condition for judging, usually using the logic operation symbol (logical operators) when judging the condition. EXPR3 the part to be executed after the execution of the statement, to change the condition for the next cycle judgment, such as add one. Wait a minute. And statement is a qualifying execution part of the program, if the program has only one row, you can omit the curly brace {}.

The following example is an example written with a for loop.

for ($i = 1; $i <=; $i + +) {
echo "This is the first". $i. " Secondary cycle
" ;
}
?>

3, switch loop, usually deal with the conditional judgment of the compound, each sub-condition, is the case instruction part. In practice, if you use many similar if directives, you can combine them into a switch loop.

The syntax is as follows

Switch (expr) {case expr1:statement1, break, Case Expr2:statement2, break, DEFAULT:STATEMENTN, break;}

The expr condition, which is usually the variable name. The ExprN after a case usually represents the value of the variable. The colon is followed by the part that meets the criteria to be executed. Note to use break to jump off the loop.

Switch (date ("D")) {
Case "Mon":
echo "Today Monday";
Break
Case "Tue":
echo "Today Tuesday";
Break
Case "Wed":
echo "Today Wednesday";
Break
Case "Thu":
echo "Today Thursday";
Break
Case "Fri":
echo "Today Friday";
Break
Default
echo "Holiday Today";
Break
}
?>

Here is the break; don't miss it, default, omitting is possible.


Obviously, the above example is very troublesome with the IF loop. Of course, in the design, the most likely to be the highest probability of the conditions at the front, the least occurrence of the conditions on the last side, you can increase the efficiency of the execution of the program. The previous example has the same probability of appearing every day, so don't pay attention to the order of the conditions.
10 days to learn the third day of PHP


Learning Purpose: Learn to build a database

In PHP, the command-line editing of MY SQL may make beginners feel very troublesome, do not matter, you download a phpMyAdmin installation, later build the editing database can rely on it.

Let's talk about its use.
After entering the phpMyAdmin, we first need to set up a database,
Language (*) Here Select Chinese Simplified, and then on the left to create a new database here fill in the database name, click Create.

Then select the database that you have created in the left drop-down menu. In the following

Create a new table in the database shop:
Name:
Number of fields:

Fill in the table name and roughly what you think of the number of fields (not enough or more of it does not matter, can be added later or default), press to execute.
Then you can start building the table.
The first column is the name of the field; the second column selects the field type:
The following are some of our common uses:
1) VARCHAR, text type
2) INT, integer type
3) Float, floating-point type
4) Date, type
5) You may ask, where is the auto-added ID? As long as you select the int type, you can select Auto_increment in the additional options below.

After you have established the table, you can see the table you created on the left, and after clicking, you can:
1) Press the structure on the right: View Modify table Structure
2) Browse by right: View the data in the table
3) Press the right SQL: Run SQL statement
4) Press Insert on right: Insert a row of records
5) on the right, clear: Delete all records in the table
6) Press DELETE on the right: Delete table

There is a very important function is import and export, when we have the program and database, we need to have a local mirror on the server, if the ASP access is simple, upload the MDB file directly, if SQL Server can also connect to the remote server for import. So in my SQL you can export all the SQL statements, to the remote server phpMyAdmin, after the database is created, press SQL, paste all the SQL statements you just copied down.

10 days to learn the fourth day of PHP


Learning Purpose: Learn to connect to a database

PHP is simply a library of functions, rich in functions that make some parts of Php quite simple. We recommend that you down a PHP function manual, the total use of the.

I'll just talk about it here. Connect to MySQL database.

1, Mysql_connect

Open the MySQL server connection.
Syntax: int mysql_connect (string [hostname] [:p ort], string [username], string [password]); return value: Integer

This function establishes a connection to the MySQL server. All of these parameters can be omitted. When using this function without any arguments, the default value of the parameter hostname is localhost, the default value for the parameter username is the owner of the PHP execution itinerary, and the parameter password is an empty string (that is, no password). The parameter hostname can be followed by a colon and a port number, which represents which port to use for MySQL connection. Of course, when using the database, using Mysql_close () to turn off the connection earlier can 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 the database in the MySQL server for subsequent data query jobs (query) processing. The success returns True, and False if it fails.

The simplest examples are:
$conn =mysql_connect ("127.0.0.1", "", "" ");
mysql_select_db ("Shop");
Connect your computer to my SQL database and open the shop database. In practical application, the point error judgment should be strengthened.

10 days to learn the fifth day of PHP
Learning Purpose: Learn to read data
Take a look at two functions first:
1, mysql_query
Sends out a query string. Syntax: int mysql_query (string query, int [link_identifier]); return value: Integer

This function sends out the query string for MySQL to do related processing or execution. If the Link_identifier parameter is not specified, the program automatically looks for the most recently opened ID. The query query string is either True or False when it is UPDATE, INSERT, and DELETE, the queried string is SELECT to return a new ID value, when False is returned, it is not successful but no return value, but the query string is wrong Miss.

2, Mysql_fetch_object return class data. Syntax: Object mysql_fetch_object (int result, int [Result_typ]); Return value: Class

This function is used to split query result results into class variables. If result has no data, a value of false is returned.

See a simple example:
$exec = "SELECT * from user";
$result =mysql_query ($exec);
while ($rs =mysql_fetch_object ($result))
{
echo "Username:". $rs->username. "
";
}
?>
Of course, there is a username field in the table user, which is similar to the one in ASP
<%
Exec= "SELECT * from User"
Set Rs=server.createobject ("Adodb.recordset")
Rs.Open exec,conn,1,1
Do and not rs.eof
Response.Write "Username:" &rs ("username") & "
"
Rs.movenext
Loop
%>
Of course first to connect to the database, generally we require_once (' conn.php '), and conn.php inside is the last time that the connection database code.

10 days to learn the sixth day of PHP


Learning Purpose: Learn to add delete modification data

mysql_query ($exec);
Single This statement can do all of the operation, the difference is $exec this SQL statement

Added: $exec = "INSERT INTO tablename (ITEM1,ITEM2) VALUES ('". $_post[' item1 ']. "',". $_post[' item1 ']. ")";

Delete: $exec = "Delete from tablename where ...";

Modified: $exec = "UPDATE tablename set item1= '". $_post[' item1 ']. "' Where ... ';

Speaking of which, we need to talk about the form and the PHP variable pass, if one of the forms
The form is submitted as a POST, then the form file can be processed using $_post[' item1 '] to get the value of the variable, and the same as get submitted is $_get[' item1 ']

Isn't it simple? But usually $exec can be problematic because your SQL statements may be long and you'll miss them. Connectors, or ' to surround a character field.
We can annotate mysql_query ($exec); The statement uses the Echo $exec, instead of outputting the $exec to check for correctness. If you are not aware of any errors in $exec, you can copy this SQL statement to phpMyAdmin to see if it has an error message. It is also important to note that we do not use sensitive strings as field names, or there are likely to be problems, such as date or something. The name of the variable, the name of the field follows a little regularity sometimes it is a benefit to oneself, the beginner should not neglect its importance.
10 days to learn the seventh day of PHP


Learning Purpose: Learn to use the session

The role of the session is many, the most used is the site within the variable transfer of the page.

At the beginning of the page we want to session_start (); open session;
Then you can use the SESSION variable, for example to assign a value is: $_session[' item ']= "Item1", to get the value is $item1=$_session[' item '; Here we may use some functions, such as determining if a SESSION variable is empty, so write: Empty ($_session[' Inum ') returns TRUE or false.

Let's take a look at a login procedure to determine if the username and password are correct.
The login form is like this: login.php







Processing files is like this
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 "";
}
}
Else
{
echo "";
}
}
Else
{
echo "";
}

?>

Conn.php is like this:
$conn =mysql_connect ("127.0.0.1", "", "" ");
mysql_select_db ("Shop");
?>

Since $_session[' AdminName ']= $username; we can write the file that verifies whether the login statement: checkadmin.php
Session_Start ();
if ($_session[' adminname ']== ')
{
echo "";
}
?>
10 days to learn the eighth day of PHP
Purpose of study: make a page display
The key is to use the limit in the SQL statement to limit the number of records displayed to a few. We need a variable $page that records the current page and a total number of records $num

For $page if not we let it = 0, if there is <0 let it also = 0, if more than the total number of pages let him = total number of pages.

$EXECC = "SELECT count (*) from TableName";
$RESULTC =mysql_query ($EXECC);
$RSC =mysql_fetch_array ($RESULTC);
$num = $RSC [0];

This will give you the total number of records
Ceil ($num/10)) If a page of 10 records, this is the total number of pages

So I can write 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 is starting from 0, so to 1
}

So $exec can write $exec = "SELECT * FROM tablename limit". ($page *10). ", 10";
One page is 10 records.

The last thing we need to do is a couple of connections:
FirstPage
">prevpage
">nextpage
">lastpage

This is a general idea, you can think how to optimize? Speaking here today, let's talk about some of the issues of attention tomorrow.

10 days to learn the nineth day of PHP

Purpose of study: precautions

1, attention do not miss the semicolon
2. Be careful not to miss the $ before the variable
3, use the session when the attention do not miss Session_Start ();

If an error occurs, you can use the following methods:
1, if the SQL statement error, comments and then output the SQL statement, note also to annotate the subsequent execution of the SQL statement
2, if the variable is empty, most of it is not passed in place, the output variable check, check the form ID and name
3. If there is a database connection error, check if my SQL is open correctly and if the connection statement is missing
4, pay attention to indentation, excluding brackets mismatch error

In the big Web site, my idea is to first build a database, to determine the role of each field, and the relationship between tables. Then design the background interface, starting from the addition of data, because the success of the add can be directly into the database validation, do a good job of adding and displaying the page, and finally the combination of the two. In general, the background will include the addition of delete changes and display, backstage no problem, the front desk is not a big problem. The front desk also needs to be aware of security and fault tolerance and the output format.

10 days to learn PHP day


Learning Purpose: Learn to upload files and send emails in PHP

The upload file form must be added enctype= "Multipart/form-data" andHere's a look at the code:

$f =& $HTTP _post_files[' file ';
$dest _dir= ' uploads ';//Set upload directory
$dest = $dest _dir. '/'. Date ("Ymd"). " _ ". $f [' name '];//me here Set file name to date plus file name to avoid duplication
$r =move_uploaded_file ($f [' Tmp_name '], $dest);
chmod ($dest, 0755);//Set the properties of the uploaded file

The uploaded file name is date ("Ymd"). " _ ". $f [' name '], which can be used later when inserting into a database, PHP is actually moving your uploaded files from the temporary directory to the specified directory. Move_uploaded_file ($f [' Tmp_name '], $dest); This is the key.

As for e-mail, it is easier to use mail () function mail ("Recipient address", "subject", "Body", "From: Sender \r\nreply-to: Sender's address");

However, mail () requires the support of the server, under Windows also need to configure the SMTP server, generally outside the Linux space is OK.

It seems that uploading files and sending emails is much simpler than ASP, as long as the functions are called. The ASP also needs to use the different components of the server, such as FSO, JMail, etc.

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