PHP Quick Dafa _php Example

Source: Internet
Author: User
Tags learn php logical operators switch loop phpmyadmin

A brief introduction to PHP syntax

1. Embedding Method:

Similar to the ASP <%,php can be <?php or yes, the end symbol is, of course, you can also specify.

2. Reference Documents :

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 top of the PHP program, PHP program before executing, will first read into the require designated to introduce the file, so that it becomes part of the PHP Program Web page. A commonly used function can be introduced into a Web page in this way.

Include use methods such as include ("myincludefile.php");. This function is typically placed in the processing section of the Process Control. The PHP Program page reads the included file when it is read. This way, you can simplify the process of executing a program.

3, annotation method :

Program code

Copy Code code as follows:

<?php
echo "This is the first example. " ; This example is a comment for C + + syntax
/* This example uses multiple lines of
Comment Mode * *
echo "This is the second example. " ;
echo "This is the third example. " ; # This example uses the UNIX Shell syntax annotation
?>

4. Variable type :

Copy Code code as follows:

$mystring = "I am a string";
$NewLine = "line Change";
$int 1 = 38;
$float 1 = 1.732;
$float 2 = 1.4E+2;
$MyArray 1 = Array ("Zi", "ugly", "Yin", "Mao");

This leads to two questions: first PHP variables begin with $, and the second PHP statement ends with a possible ASP programmer that doesn't fit. These two omissions are also the most error in the procedure.

5. Operation Symbol :

Mathematical operations: Symbolic meaning
+ addition operation
-Subtraction operation
* Multiplication operation
/Division Operations
% take remainder
+ + Additive
--Diminishing

String Operations:

There is only one operation symbol, the period of English. It can concatenate strings into a new merged string. Similar to & in ASP

Program code

Copy Code code as follows:

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

Here also leads to two questions, first PHP output statement is echo, the second similar to the <%= variable%>,php in ASP can also <?= variables? >.

Logical operations:

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

Learning objectives: Mastering PHP's Process Control

1, If ... else loop has three kinds of structure

The first is to use only if conditions, as a simple judgment. Explained as "What to do if something happens". The syntax is as follows:

if (expr) {statement}

The condition that expr is judged is usually used as the criterion of logic operation symbol. and statement for the implementation of the conditions of the program, if the program has only one line, you can omit the curly braces {}.

Example: This example omits curly braces.

Program code

Copy Code code as follows:

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

It is particularly noteworthy here that the decision whether equality is = = rather than =,asp programmer may make this error, = is assignment.

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

Program code

Copy Code code as follows:

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

The first two, except if, plus the condition of else, can be explained as "What to do if something happens, how to deal with it". The syntax is as follows

if (expr) {statement1} else {Statement2} example: The above example is modified to more complete processing. Where else is due to only one row of instructions, so no curly braces are added.

Program code

Copy Code code as follows:

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

The third type is recursive if. else loops, usually used in a variety of decision judgments. It will be several if.. Else take to combine the use of processing.

Look directly at the example below

Program code

Copy Code code as follows:

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

The previous example uses only the two-level if. else loop, to compare A and b two variables. You actually want to use this recursive if. else loop, please use caution, because too many layers of the loop can make the logic of the design problem, or less dozen curly braces, will cause the program to appear inexplicable problems.

2, for loop on pure 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 the condition of judgment, which is usually judged by the logic operation symbol (logical operators). EXPR3 the part to be executed after the execution of statement to change the condition for the next round of judgment, such as add one. Wait a minute. and statement for the implementation of the conditions of the program, if the program has only one line, you can omit the curly braces {}.

The following example is an example written in the For loop.

Program code

Copy Code code as follows:

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

3, switch cycle , usually deal with the conditions of the compound judgment, each child condition, is the case instruction part. If you use many similar if instructions on the implementation, you can synthesize it 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, usually the variable name. The ExprN after the case usually represents the value of the variable. The colon is followed by the part that meets the condition. Notice that you want to jump off the loop with a break.

Program code

Copy Code code as follows:

<?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 "Today's Holiday";
Break
}
?>

Here is the need to pay attention to the break; do not omit, default, omit is OK.

Obviously, the example above is cumbersome with the IF loop. Of course, in the design, the most likely to have the highest probability of the first, the least occurrence of the conditions on the last side, you can increase the efficiency of the implementation 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.

Learning objectives: Learn to build a database

In ASP, if you are an Access database you can directly open access to edit the MDB file, if it is SQL Server you can open Enterprise Manager to edit the SQL Server database, but in PHP, my SQL command line editing may make beginners feel very troublesome, It does not matter, you download a phpMyAdmin installation, after the establishment of 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 choose Chinese Simplified, and then on the left to create a new database here to fill out the name of the database, click to create.

Then, in the left Drop-down menu, select the database that you have created. 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 the number of fields (not enough or more does not matter, later can be added or default), according to the implementation.
Then you can start building the table.
The first column is the name of the field, and 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 automatically added ID? Just select the int type and select Auto_increment on the back of the extra.

After you set up the table, you can see the table you created on the left, and after you click, you can:
1) Press the structure on the right: view the modified table structure
2) Browse to the right: view the data in the table
3 Press the SQL on the right: run the SQL statement
4) Press Right insert: Insert a row record
5) to the right of the empty: delete all records in the table
6) Press the Delete on the right: delete the table

There is also a very important function is to import and export, when we have done 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 it is SQL Server can also connect remote server to import. So in my SQL you can export all the SQL statements, to the remote server phpMyAdmin, the database after the creation of SQL, sticky paste you just copied down all the generated SQL statements.

Learning Purpose: Learn to connect to a database

PHP is simply a library of functions, and rich functions make php quite simple in some places. I suggest everyone down a PHP function manual, the total use of.

I'm just going to say a little bit here. Connect 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 stroke, 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, representing which port is used to connect to MySQL. Of course, when using a database, using Mysql_close () to turn off the connection early 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. Returns true successfully, and returns False if failed.

The simplest example is:
$conn =mysql_connect ("127.0.0.1", "" "," ");
mysql_select_db ("Shop");
Connect my SQL database and open the shop database. In practical application, we should strengthen the point error judgment.

Learning Purpose: Learn to read data

Look at two functions first:
1, mysql_query
Send 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 you do not specify the Link_identifier parameter, the program automatically looks for the most recently opened ID. If the query string is Update, Insert, and Delete, the return may be true or false, and the query's string is a Select that returns a new ID value, and when false, it is not a successful execution but no return value, but a string of queries that 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. Returns the value of False if result has no data.

Look at a simple example:

Program code

Copy Code code as follows:

?
$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 table user, which is similar to the one in ASP

Program code

Copy Code code as follows:

<%
Exec= "SELECT * from User"
Set Rs=server.createobject ("Adodb.recordset")
Rs.Open exec,conn,1,1
Do as not rs.eof
Response.Write "Username:" &rs ("username") & "<br>"
Rs.movenext
Loop
%>

Of course, we have to connect the database first, generally we require_once (' conn.php '), and conn.php inside is the last time the code that connects the database.

Learning Purpose: Learn to add delete modify data

mysql_query ($exec);
Single This statement can perform all the operations, the difference is $exec this SQL statement

Add: $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'll talk about forms and PHP variable passing, if one of the forms <input name= "item1" type= "text" id= "Item1" >
The form is submitted by POST, then processing the form file can get the value of the variable with $_post[' item1 ', which is also the $_get[' item1 ' submitted.

Is it simple? But usually $exec can be problematic because your SQL statements may be very long, and you'll miss out. Connectors, or ' to surround character fields.
We can annotate mysql_query ($exec); statements use echo $exec instead to output $exec to check for correctness. If you are not aware of any $exec errors, you can copy the SQL statement to phpMyAdmin and see its error message. It is also important to note that we do not use sensitive strings as field names, otherwise there are likely to be problems, such as date or something. The name of the variable, the name of the field follow a little rule sometimes it's a good thing for yourself, and beginners can't ignore its importance.

Learning Purpose: Learn the use of Session

The role of a lot of sessions, the most use is the site within the page variable transfer. At the beginning of the page we want to session_start ();
Then you can use the session variable, for example, to assign the value is: $_session[' item ']= ' item1 ', to get the value is $item1=$ _session[' item '; Here we may use some functions, such as to determine whether a session variable is empty, so to write: empty ($ _session[' inum ') returns TRUE or false.

Here is a comprehensive look at a login program to determine whether the user name password is correct.
The landing form is this: login.php

Program code

Copy Code code as follows:

<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" >
&LT;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" >
&LT;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>

Working with files is like this

Program code

Copy Code code 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

Copy Code code as follows:

?
$conn =mysql_connect ("127.0.0.1", "" "," ");
mysql_select_db ("Shop");
?>

Because $_session[' adminname ']= $username; we can write this to verify that the file is logged: checkadmin.asp

Program code

Copy Code code as follows:

?
Session_Start ();
if ($_session[' adminname ']== ')
{
echo "<script>alert (' please Login a '); location.href= ' login.php ';</script>";
}
?>

Learning Purpose: Make a paging display

The key is to use the limit in the SQL statement to qualify the displayed records from several to several. 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.

Copy Code code as follows:

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

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

So you can write that.

Copy Code code 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 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:

Program code

Copy Code code as follows:

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

This is a general idea, we can think how to optimize?

Purpose of study: matters needing attention

Because I was first to learn ASP, so do PHP when you will find that many places need to adapt.

1, pay attention not to miss the semicolon
2, pay attention not to miss the variable before the $
3, use the time of session to pay attention not to omit session_start ();

If an error occurs, you can use the following methods:
1, if it is an error in the SQL statement, then the output of the SQL statement, note that you also want to comment on the subsequent execution of the SQL statement
2, if the variable is empty, most of it is not passed in place, output variables check, check the ID and name of the form
3, if the database connection error, check to open my SQL correctly and whether the connection statement is missing
4, pay attention to indentation, excluding the parentheses do not match the error

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

Learning Purpose: Learn to upload files and email in PHP

Upload file form must add Enctype= "Multipart/form-data"
and <input type= "file" name= "file" >
Let's take a look at the code:

Copy Code code as follows:

$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 filename 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 the database, PHP actually moves the file you uploaded from the temporary directory to the specified directory. Move_uploaded_file ($f [' Tmp_name '], $dest); That's the key.

It's easier to send mail, you can use the mail () function

Mail ("Recipient address", "subject", "Body", "From: Sender Reply-to: Sender's address");

However, mail () requires the support of the server, in 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 you call a function. ASP also needs to use different components of the server such as FSO, JMail and so on.

is not soon to learn PHP, I hope that small partners can enjoy.

Related Article

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.