Php & amp; mysql three-day pass 3 I. basic functions <br/> Welcome to the third and last lessons in this tutorial. If you have learned the first and second lessons, you have mastered MyS 1 and 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 () and require (). These two functions have very little difference, but they are very important. so we need to study them carefully. The require () function works in a similar way as XSSI. no matter which part of the program uses this function, only the program starts to run, the header file content is processed as part of the program itself. Therefore, if you use the require () function in a condition determination statement, the header file will be included even if the condition is not true.
The include () function only includes the header file content when this statement is executed. If the program does not run here, PHP will not care about it. This means that when you use include in the condition determination part, it will work exactly as you want.
In addition, if you use the require () function and the header file you specified does not exist, the program stops running and produces errors. If you use include (), the program generates a warning message, but continues to run. You can try it yourself, run the following program, replace include () with require (), and then compare the results of the two programs.
Include ("emptyfile. inc ");
Echo "Hello World ";
?>
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.
$ Db = mysql_connect ("localhost", "root ");
Mysql_select_db ("mydb", $ db );
?>
<Br/> <? Php echo $ title?> <Br/>
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.
$ Title = "Hello World ";
Include ("header. inc ");
$ Result = mysql_query ("SELECT * FROM employees", $ db );
Echo"
\ N ";Echo"
Name |
Position |
\ N ";While ($ myrow = mysql_fetch_row ($ result )){Printf ("
% S |
% S |
\ N ", $ myrow [1], $ myrow [2], $ myrow [3]);}Echo"
\ 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 how $ title is defined before the header file contains header. inc. 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 need to do is to get a proper value for the $ title variable in each main program.
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. Strlen () is a simple function that tells 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.
If ($ submit ){
If (! $ First |! $ Last ){
$ Error = "Sorry, you must enter all columns! ";
} Else {
// Process table input
Echo "thank you! ";
}
}
If (! $ Submit | $ error ){
Echo $ error;
?>
} // If ends
?>
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 whether both the $ first and $ last 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 about the strlen () function. 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 the length of $ first and $ last.
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;
?>
} // If ends
?>
You can run this program and enter six or less words. This verification is simple, but it is very effective?>
3. process regular expressions
Let's talk about using the ereg () and eregi () functions to 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. [[: Alpha:] is an easy 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. let's go to the next page.
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 $ myname in the program. if you create a function and want this function to use the $ myname variable (with the same value), that is not acceptable. You can create a variable named $ myname in the function. These 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.
Function addnum ($ first, $ second ){
$ Newnum = $ first + $ second;
Return $ newnum;
}
Echo addnum (4, 5 );
?>
That's all! First, we created the first function of our own. We have defined two new variables, $ first and $ second. pay attention to how they are defined. When calling this function, you need to assign the values-4 to $ first and 5 to $ second in the order they appear. 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:
Function do_error ($ error ){
Echo "Oh, it seems a problem...
";
Echo "system reported error: $ error. \ n
";
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 );
}
?>
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 the @ symbol before the mysql_connect () 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:
Function db_query ($ SQL ){
Global $ db;
$ Result = mysql_query ($ SQL, $ db );
Return $ result;
}
$ SQL = "SELECT * FROM mytable ";
$ Result = db_query ($ SQL );
?>
This is a simple function, but it is important that you do not have to pass the $ db variable when calling this function-you can use the word global to allow the function to access this 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:
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 );
?>
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.