"Turn" a day to learn PHP (turn)
Just one day, as long as you look and learn with your heart, it will be OK.-
Here I hope you need to understand a little, this is just talking about how to get started quickly, better understand php! Basic knowledge of PHP can also be mastered! PHP language is profound! It's not a day or two to learn! It's a long way to go!
Below I green Apple to take everyone into the path of getting into PHP
Description
For the time being, I am using Apache Web server and my SQL as the Web servers and databases, under the environment of php-4.3.3. Of course, simple to build and access to view the database PHPMYADMIN no less
You need to understand the basics of HTML here! No basic knowledge of HTML! can go to Baidu or Google search! It's simple! There's not much to say here.
All right, let's get started! Let's start with PHP as an apple! Eat him in a mouthful!
No more wordy! Here we go
Eat an apple
1. Embedding Method:
ASP-like <%,php can be <?php or <?, the end symbol is, of course, you can also specify.
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:
<?php
echo "This is the first example. \ n "; This example is a comment for C + + syntax (PHP comments are similar to C!). )
/* 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, first the PHP variable begins with $, the second PHP statement ends, and the ASP programmer may not be able to adapt. These two omissions are also the most procedural errors.
5, Operation symbols:
Number * * Illegal words have been blocked * * Counted:
Symbolic meaning
+ addition operation
-Subtraction operation
* Multiplication operation
/Division Operation
% take remainder
+ + Cumulative
--Diminishing
String Operations:
The arithmetic symbol has only one, is the English period. It can concatenate strings together and become merged new strings. & In ASP-like
<?
$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 <?= variable?>.
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)
Talk about Process Control.
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.
<?php
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.
<?php
if ($state ==1) {
echo "haha;
echo "<br>";
}
?>
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.
<?php
if ($state ==1) {
echo "haha";
echo "<br>";
}
else{
echo "hehe";
echo "<br>";
}
?>
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
<?php
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.
<?php
for ($i = 1; $i <=; $i + +) {
echo "This is the first". $i. " Sub-cycle <br> ";
}
?>
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.
<?php
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.
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.
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.
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. " <br> ";
}
?>
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") & "<br>"
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.
A small two-piece command can do the work of reading the data.
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're going to talk about the form and PHP variable delivery, if one of the forms <input name= "item1" type= "text" id= "Item1" >
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.
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
<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" >
<tr class= "tdbg" >
<TD colspan= "2" ><div align= "center" >administrators login</div></td>
</tr>
<tr class= "tdbg" >
<td><div align= "center" >Username</div></td>
<td><div align= "center" >
<input name= "username" type= "text" id= "username" >
</div></td>
</tr>
<tr class= "tdbg" >
<td><div align= "center" >Password</div></td>
<td><div align= "center" >
<input name= "password" type= "password" id= "password" >
</div></td>
</tr>
<tr class= "tdbg" >
<TD colspan= "2" ><div align= "center" >
<input type= "Submit" name= "submit" value= "Submit" >
<input type= "reset" name= "Submit2" value= "Clear" >
</div></td>
</tr>
</table></td></form>
</tr>
</table>
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 "<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");
?>
Since $_session[' AdminName ']= $username; we can write the file that verifies whether the login statement: checkadmin.php
<?
Session_Start ();
if ($_session[' adminname ']== ')
{
echo "<script>alert (' please Login first '); location.href= ' login.php ';</script>";
}
?>
Make a paging 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:
<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>
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.
Learn to upload files and send emails in PHP
Upload file form must be added enctype= "Multipart/form-data"
and <input type= "file" name= "file" >
Here'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 sending e-mail, it is easier to use the 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.
A day to learn PHP said here, want to tell everyone is PHP can be a day, but proficient in never is a day, but also need to study their own
"Turn" a day to learn PHP (turn)