PHP + MySQL 3

Source: Internet
Author: User
Tags ereg mysql tutorial php email php website

 

PHP/MySQL 3-3 days

Original Author: Graeme merrall

Directory

PHP/MySQL tutorial-Day 1 
I. Introduction to PHP/MySQL
Ii. Install MySQL
3. install PHP
4. The first script
V. load databases
Vi. Test

PHP/MySQL tutorial-Day 2 
1. While Loop
II. If-Else
3. The first program script
4. send data to the server
5. modify data
6. Complete procedures

PHP/MySQL tutorial-Day 3 
I. Basic functions
Ii. Data Verification
3. Process Regular Expressions
Iv. Simple Method
5. Advanced Skills

I. Basic functions

Welcome to the third and last course of this tutorial. If you have learned the first and second lessons, you have mastered the Basic installation and programming knowledge of MySQL and PHP. Next we will introduce some other PHP functions, which may be useful to you and make your development process easier. First, let's look at the header file.

Do you know some basic concepts of header files? The header file is an external file whose content is included in the main program. The method is also very simple: reference the header file name in the program file, this header file will be included. Using the header file in PHP involves two functions:Include ()AndRequire (). These two functions have very little difference, but they are very important. So we need to study them carefully.Require ()The function works in a similar way as xssi. No matter which part of the program uses this function, the content of the header file is processed as part of the program when the program starts to run. Therefore, if you useRequire ()Function, the header file will be included even if this condition is not true.

WhileInclude ()The function only includes the header file content when executing this statement. If the program does not run here, PHP will not care about it. This means that you useIncludeIt will work exactly as you want.

Also, if you useRequire ()Function, but the header file you specified does not exist, the program will stop running and generate an error. If you useInclude ()The program generates a warning message, but continues to run. You can give it a try, run the following program, and thenInclude ()ChangeRequire ()And then compare the results of the two programs.

  <HTML>

<Body>

<? PHP

Include ("emptyfile. Inc ");

Echo "Hello World ";

?>

</Body>

</Html>

I like to name the header file as. Inc, so that the header file can be distinguished from general programs. If you do the same, modify the configuration file of the web server software so that it can process the. inc file as a PHP file. Otherwise, hackers may guess your header file name and display the header file content in plain text in a browser. At this time, if your header file contains some confidential information (such as database passwords), it will be terrible.

So what do you do with header files? Very easy! Put the content that is common to all programs in the header file. Like the HTML file header, footer, database connection code, and some functions you have defined. Copy the following text to a file and save it as header. Inc.

  <? PHP

$ Db = mysql_connect ("localhost", "root ");

Mysql_select_db ("mydb", $ dB );

?>

<HTML>

<Head>

<Title>

<? PHP echo $ title?>

</Title>

</Head>

<Body>

<Center> <H2> <? PHP echo $ title?> </H2> </center>

After that, create another file named footer.txt, which can contain some text and tags used at the end of the program.

Now let's create another file, which contains the real PHP program code. Try the following code. Of course, make sure that the MySQL database server is running.

  <? PHP

$ Title = "Hello World ";

Include ("header. Inc ");

$ Result = mysql_query ("select * from employees", $ dB );

Echo "<Table border = 1>/N ";

Echo "<tr> <TD> name </TD> <TD> position </tr>/N ";

While ($ myrow = mysql_fetch_row ($ result )){

Printf ("<tr> <TD> % S </TD> <TD> % S </tr>/N", $ myrow [1], $ myrow [2], $ myrow [3]);

}

Echo "</table>/N ";

Include ("footer. Inc ");

?>

See what happened? The content in the header file is merged into the program, and PHP executes all the code. Note that before the header file contains header. Inc$ TitleHow is it defined. The code in header. INC can access its value. In this way, the webpage title is changed. Now, you can use the header file header of header. Inc in any program. All you have to do is$ TitleTake a proper value for the variable.

Header files, HTML, condition-based judgment statements, and cyclic statements. When added, you can use the most concise code to write various complex programs with different functions. When using the function at the same time, the header file can make full use of it, which we will see later.

Next, we will introduce some highlights: data verification.>

Ii. Data Verification

Imagine this situation: we have designed all the databases properly. Now we ask the user to enter the information to write it to the database. Assume that you have a field that requires numeric type information, such as price, while a cute user enters text information in this column, the execution process of your application fails. MySQL Databases refuse to accept the text data you provide in SQL statements and submit a "solemn protest" to you ".

What should we do? You must use data verification to prevent the above situations.

To put it simply, data verification refers to checking the data (usually transmitted through HTML tables) to see if it complies with certain rules. Rules can be diverse. For example, a data element cannot be empty, or the content of a data item must meet certain requirements (for example, in the preceding example, the content must be a number rather than a text, or the email address must contain a "@" character ).

Data verification can be performed at either the server or the client. PHP is used for data verification at one end of the server, while JavaScript or other client-side scripting languages can provide the client-side data verification function. This article is about PhP, so we will focus on server-side verification here. If you want to find some off-the-shelf data comparison programs running on the client, you can go to the monkey library.

If you leave the database aside for the moment, let's talk about the data verification method of PHP. If you want to (or, if you want to record the data we want to verify), you can add other fields to the employee database created earlier, which is very simple, use the alter Statement of MySQL.

There are several PHP functions that can be used for data verification. Some are simple and some are complicated. WhereStrlen ()Is a simple function that can tell us the length of a variable.

More complex:Ereg ()This function can process the complete regular expression for complex verification. I don't want to talk too deeply about regular expressions, because many books are dedicated to this issue. However, I will give some simple examples on the next page.

Let's start with a simple example. The following program checks whether a variable exists.

  <HTML>

<Body>

<? PHP

If ($ submit ){

If (! $ First |! $ Last ){

$ Error = "Sorry, you must enter all columns! ";
} Else {

// Process Table Input

Echo "Thank you! ";

}
}

If (! $ Submit | $ error ){

Echo $ error;

?>

<P>

<Form method = "Post" Action = "<? PHP echo $ php_self?> ">

Column 1: <input type = "text" name = "name" value = "<? PHP echo $ first?> "> <Br>

Column 2: <input type = "text" name = "surname" value = "<? PHP echo $ last?> "> <Br>

<Input type = "Submit" name = "Submit" value = "input information">

</Form>

<? PHP

} // If ends

?>

</Body>

</Html>

The key part of this program is the nested condition judgment statement. The first layer checks whether the user has pressed the send data button. If yes, the program then checks$ FirstAnd$ LastWhether both variables exist. That | the symbol "or", and! It indicates "not ". The general language of the program is "If $ first does not exist or $ last does not exist, set the $ error variable to the following value ."

Next, let's further examine the length of a text segment. This is necessary to check the user password, because you do not want some lazy users to enter only one or two passwords, and may ask them to enter six long passwords.

We have already talked aboutStrlen ()This function is now available. It simply returns a number that is equal to the number of characters in the variable to be tested. Here, I will modify the above program and check it$ FirstAnd$ Last.

  <HTML>

<Body>

<? PHP

If ($ submit ){

If (strlen ($ first) <6 | strlen ($ last) <6 ){

$ Error = "Sorry, you must enter all columns! ";

} Else {

// Process Table Input

Echo "Thank you! ";

}

}

If (! $ Submit | $ error ){

Echo $ error;

?>

<P>

<Form method = "Post" Action = "<? PHP echo $ php_self?> ">

Column 1: <input type = "text" name = "name" value = "<? PHP echo $ first?> "> <Br>

Column 2: <input type = "text" name = "surname" value = "<? PHP echo $ last?> "> <Br>

<Input type = "Submit" name = "Submit" value = "input information">

</Form>

<? PHP

} // If ends

?>

</Body>

</Html>

You can run this program and enter six or less words. This verification method is simple but effective.>

3. Process Regular Expressions

Let's talk a little bit about UsageEreg ()AndEregi ()The two functions process regular expressions. As I mentioned earlier, some of these functions are simple and complex, depending on your actual needs.

With regular expressions, you can check a string, search for some schema patterns, and determine whether these patterns meet your requirements. The most common usage includes checking whether the email address is valid (of course, even if this method is determined to be valid, there is no guarantee that the email address actually exists ).

We will not detail the complex details of regular expressions here, but just give several examples. You can use the table used in the previous page to copy the corresponding program code and add it to the following code segment to see how it works.

First, make sure that only letters are allowed in each column of the table. The following regular expression is true when the user inputs one or more lower-case letters, and the input number is not allowed:

If (! Ereg ("[A-Z]", $ first) |! Ereg ("[A-Z]", $ last )){

Now let's go further and check whether the string length is four to six characters long. Use[[: Alpha:]Is a simple way to check whether a character is a letter. Check the number of characters in braces. Note that ^ and $ represent the start and end of the string respectively.

If (! Ereg ("^ [: Alpha:] {4, 6} $", $ first) |! Ereg ("^ [[: Alpha:] {4} $", $ last )){

Finally, we construct a regular expression to verify the validity of the email address. The results of this test method have already been discussed. Nothing is perfect, but the program I provided below is still very effective.

My baby program is from the PHP email discussion group. That's a good place to go. Yes, this program looks a little messy.

  If (! Ereg ('^ [-! # $ % &/'* + //./0-9 =? A-Z ^ _ 'a-z {|} ~] + '.

'@'.

'[-! # $ % &/'* + // 0-9 =? A-Z ^ _ 'a-z {|} ~] + /.'.

'[-! # $ % &/'* + //./0-9 =? A-Z ^ _ 'a-z {|} ~] + $ ', $ Last )){

Don't spend too much time investigating this code. Please go to the next page first.>

Iv. Simple Method

What about the regular expression above? Interesting, right? It would be interesting to write such a program in every program that needs to check the email address ?! Think about it. You have to write a program that is so messy. you have to write it so many times !... However, of course, there are simpler methods.

Do you still remember the header files we have learned before? It allows us to write a program, such as the email address check program, and then include this program into multiple programs. In this way, when we want to rewrite this program, we only need to change one place, and there is no need to modify multiple files.

However, to do this, we must use functions.

We have used functions many times. Every time we query the database or check the string length, we use functions. These functions are provided by PHP. If you are an enthusiastic programmer, you can use your own functions to expand the functions of PHP. However, this part of content is too advanced for this tutorial. The functions we want to create are not those, but the functions written in the PHP script program.

A function is a piece of program code. We can pass one or more values to this code. Then this code will process the data we pass to it and return a value. Based on actual needs, functions can be very simple or complex. But as long as we input a number and then we can get a number, you can check whether it is complicated or simple! This is the cute part of the function.

Functions in PHP are similar to those in C. When defining a function, you must specify the data that the function needs to receive. At first, it seems that I don't quite understand why it needs to receive data, but this can prevent some weird problems. The function can do this because all the variables in the function are private variables, that is, they only exist within the function. For example, you have a variable named$ MynameIf you create a function and want it to use$ MynameVariable (same value), that is not acceptable. You can create a variable in the function.$ MynameThe two variables can get along with each other and get different values. But I do not recommend that you do this! If you do, you may be confused when you modify the program six months later.

Now let's create a function. Let's make it simple first. We need to give it a name to specify the variable it will receive. Before calling this function, we have to define this function.

 

  <HTML>

<Body>

<? PHP

Function addnum ($ first, $ second ){

$ Newnum = $ first + $ second;

Return $ newnum;

}

Echo addnum (4, 5 );

?>

</Body>

</Html>

That's all! First, we created the first function of our own. We have defined two new variables,$ FirstAnd$ Second, Pay attention to how they are defined. When calling this function, you need to assign the values-4 to the two variables in the order they appear.$ First, 5 assigned$ Second. Then we simply add the two numbers together and return the results. "Return" indicates sending the result back. In the last part of the program, we will display the number 9.

Let's create a function to help our database applications. How about a function that can properly handle errors? Try the following program:

  <HTML>

<Body>

<? PHP

Function do_error ($ error ){

Echo "oh, it seems a problem... <br> ";

Echo "system reported error: $ error./n <br> ";

Echo "it is best to temporarily close the website and notify the system administrator. ";

Die;

}

If (! $ Db = @ mysql_connect ("localhost", "user", "password ")){

$ Db_error = "unable to connect to MySQL Database ";

Do_error ($ db_error );
}

?>

</Body>

</Html>

Before running the program, close the MySQL database or use the wrong user name or password. You will see friendly and useful error messages. Careful friends will notice thatMysql_connect ()The @ symbol before the function. It will suppress system error information, so that the program can only get the relevant error information from the do_error () function. You will also notice that we can pass a variable defined elsewhere as a parameter to the function, instead of assigning a value directly during the call.

Remember that I used private variables in functions? This is not entirely true. In fact, you can allow the function to access variables outside the function. You may need to write a function to query the database and display the result on multiple webpages. You do not want to pass the database connection ID to the function every time. In this case, you can define the connection ID as a global variable. For example:

  <HTML>

<Body>

<? PHP

Function db_query ($ SQL ){

Global $ dB;

$ Result = mysql_query ($ SQL, $ dB );

Return $ result;

}

$ SQL = "select * From mytable ";

$ Result = db_query ($ SQL );

?>

</Body>

</Html>

This is a simple function, but it is important that you do not have to pass$ DBVariable-you can use the word global to allow the function to access the variable. You can define multiple global variables in this Statement. Each global variable is separated by a comma.

Finally, you can use optional parameters, so that you are already a real expert. The key point here is to specify a default value when defining a parameter in a function. When you call this function, if other values are not specified for this parameter variable, the function automatically assigns the default value to this variable. If you specify other values, the default value does not work.

Not quite clear? For example, when you connect to a database, you almost always connect to the same server and use the same user name and password. However, you also need to connect to other servers. Take a look at the following program:

  <HTML>

<Body>

<? PHP

Function db_connect ($ host = "localhost", $ user = "username", $ pass = "Graeme "){

$ Db = mysql_connect ($ host, $ username, $ password );

Return $ dB;

}

$ Old_db = db_connect ();

$ New_host = "site.com ";

$ New_db = db_connect ($ new_host );

?>

</Body>

</Html>

It's cool, isn't it? When defining a function, the variables used inside the function are also defined. When this function is called for the first time, all parameter variables use the default value. During the second call, the server name has changed, but the user name and password have not changed. Great!

Think about where you can use the function. You can use functions for data verification to complete common functions. I used many functions to process the text displayed on a web page. I can check, parse, and modify the text at one time to add line breaks and HTML tags.

Now, I want to give you some advice.>

5. Advanced Skills

We have a lot to learn about database development. If you have not learned how to design databases, and how to run databases reliably on different platforms, please read this book quickly. This capability will bring you immeasurable benefits. In the long run, it will save you a lot of time and energy. Also, learn MySQL carefully. This is a complex and interesting database with many good documents. The table structure, data type, and SQL of the learning database. If you have mastered SQL, you can do a lot of practical work.

Finally, PHP is available. Almost everything you want can be found on the PHP website, including comprehensive documents, discussion content of email discussion groups, program code libraries, and so on. An excellent way to learn about PhP is to study the examples provided in the user manual and check the online code. Code published by netizens includes many functions and classes, which can be directly used in your own programs without having to start from scratch. In addition, if you encounter problems, the email discussion group is a very useful resource. PHP developers also participate in e-mail discussion groups, and many experienced experts can help you solve problems.

Wish you a smooth programming and everything went well!

 

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.