In this lesson, we want to learn how to increase the intelligent processing capacity of the Web page.
Basic functions
Welcome to the third and final lesson of this tutorial. If you've learned the first and second lessons, you've mastered the basics of installing and programming MySQL and PHP. Here are some of the other functions of PHP that might be useful to you and make your development process simpler. First, let's look at the document.
You should know some basic concepts of the header file, right? The header file is an external file whose contents are included in the main program. The method is also simple: referencing the header filename in the program file, the header file is included. Using header files in PHP involves two functions: include () and require (). These two functions are very small, but very important, so we have to study carefully. The Require () function works like a xssi, and regardless of which part of the program is used, the contents of the header file are processed as part of the program itself. Therefore, if you use the Require () function in a conditional decision statement, the header file is included even if the condition is not true.
The Include () function only contains the contents of the head file when executing to this statement. If the program is not running here, PHP will not control it. This means that when you use include in the Conditional decision section, it works exactly the way you want it to.
Also, if you use the Require () function and the header file you specify does not exist, the program stops running and generates an error. If you use include (), the program produces a warning message, but it continues to run. You can try it yourself, run the following program, and then replace the include () with require () and compare the results of the two programs.
<html>
<body>
<?php
Include ("Emptyfile.inc");
echo "Hello World";
?>
</body>
</html>
I like the suffix name of the head file as. Inc, so that you can distinguish the head file from the general program. If you do the same, please modify the Web server Software configuration file so that it can handle the. inc file as a PHP file. Otherwise, hackers may guess your header file name, and then use the browser to display the contents of the head file in plain text format. At this point, if you have some confidential information (such as a database password, etc.) in your header file, that's bad.
So, what do you do with a header file? Very simple! Put the content that is common to all programs in the header file. Like HTML file headers, footnotes, database connection codes, and some of the functions you've defined. Copy the following text into 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>
Enter and then create another file, named Footer.txt, which can contain some of the text and tags used at the end of the program.
Now we're going to create a file that contains the real PHP code. Try the following code, of course, to confirm 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>";
echo "<tr><td> name </td><td> position </tr>";
while ($myrow = Mysql_fetch_row ($result)) {
printf ("<tr><td>%s%s</td><td>%s</tr>", $myrow [1], $myrow [2], $myrow [3]);
}
echo "</table>";
Include ("Footer.inc");
?>
See what happened? The contents of the header file are merged into the program, and PHP executes all the code. Note how $title is defined before the Header.inc header file is included. The code in HEADER.INC can access its value. This way, the title of the page is changed. Now that you can use the Header.inc header file in any program, all you have to do is to get the appropriate value for the $title variable in each main program.
header files, HTML, conditional decision statements, and looping statements, which are added to some, you can use the most concise code to write various complex programs of varying functions. When used in conjunction with a function, the header file is more effective, as we'll see later.
Ii. Data validation
Imagine the situation: we've designed the database, and now ask the user to enter information to write to the database. Suppose you have a field that requires a numeric type of information, such as a price, and some lovely user enters text information in this column, which causes the execution of your application to fail.
The MySQL database refuses to accept the type of data you provide in the SQL statement, and presents you with a "solemn protest".
What do we do? You want to use data validation to prevent the above situation from happening.
Simply put, data validation means that we check the data (usually the user passes through the HTML form) to see if it complies with certain rules. Rules can be various, such as a data element cannot be empty, or require that the content of a data item must meet certain requirements (for example, in the previous example, the requirement must be a number rather than text, or the email address must contain a "@" word, etc.).
Data validation can be done either at the server or at the client. PHP is used for data validation at one end of the server, while JavaScript or other client script programming languages can provide data validation for the client. This article is about PHP, so we are here to focus on server-side checksums. If you want to find some ready-made, on the client run the data than the test procedures, then you can go to the Monkey Library to see.
To put the database aside for the time being, let's talk about the data validation method of PHP first. If you prefer (or you want to record the data we want to verify), you can add the other fields to the employee database that you built earlier, very simply by using the MySQL ALTER statement.
There are several PHP features that can be used to work with data validation, some simple and some more complicated. where strlen () is a relatively simple function that tells us the length of a variable.
A bit more complicated is ereg (), which can handle a complete regular expression for complex checksums. I don't want to talk too much about regular expressions, because a lot of books are written about this problem. But I'll give some simple examples on the next page.
Let's start with a simple example. The following program checks to see if a variable exists.
<html>
<body>
<?php
if ($submit) {
if (! $first | |! $last) {
$error = "Sorry, you must fill in all the columns!" ";
else {
Working with form entries
echo "Thank you!" ";
}
}
if (! $submit | | $error) {
Echo $error;
?>
<P>
<form method= "POST" action= "<?php echo $PHP _self?>" >
First column: <input type= "text" name= "name" value= "<?php echo $first?>" ><br>
Second column: <input type= "text" name= "surname" value= "<?php echo $last?>" ><br>
<input type= "Submit" name= "submit" value= "Input Info" >
</form>
<?php
}//If End
?>
</body>
</html>
The key place in this program is the nested conditional decision statement. The first level checks whether the user presses the button that sends the data. If so, the program then checks whether the $first and $last two variables exist. that | | Symbol denotes "or", and! The symbol denotes "non". The program is described in general language as "if the $first does not exist or the $last does not exist, then the $error variable is placed to the following value." ”
Next, we'll go further and check the length of the text. This check for user passwords is necessary because you do not want some lazy users to enter a password of only one or two words, which may require them to enter a six-bit long password.
We have already talked about the function of strlen (). It simply returns a number that equals the number of characters contained in the variable being measured. Here, I modify the above procedure, check the length of $first and $last.
<html>
<body>
<?php
if ($submit) {
if (strlen ($first) < 6 | | strlen ($LAST) < 6) {
$error = "Sorry, you must fill in all columns!" ";
else {
Working with form entries
echo "Thank you!" ";
}
}
if (! $submit | | $error) {
Echo $error;
?>
<P>
<form method= "POST" action= "<?php echo $PHP _self?>" >
First column: <input type= "text" name= "name" value= "<?php echo $first?>" ><br>
Second column: <input type= "text" name= "surname" value= "<?php echo $last?>" ><br>
<input type= "Submit" name= "submit" value= "Input Info" >
</form>
<?php
}//If End
?>
</body>
</html>
You can perform this program and enter six words or less than six words. This check is simple, but it works?>
Iii. dealing with regular expressions
Let's talk a little bit about regular expressions with ereg () and eregi () two functions. As I mentioned earlier, some of these functions are simple, and some are very complex, which depends on your actual needs.
With regular expressions, you can examine a string and search for some of its structural patterns to determine whether these patterns meet your requirements. The most common uses include checking that an e-mail address is valid (and, of course, that the email address does not really exist even if the method is judged to be valid).
Here we do not examine the complex details of regular expressions, just give a few examples. You can use the table used in the previous page-copy the appropriate program code and add it to the following code snippet to see how it works
First, we want to make sure that the columns in the table can only enter letters. The following general expression is true when the user enters one or more lowercase letters, and the input number is not allowed:
if (!ereg ("[A-Z]", $first) | |!ereg ("[A-Z]", $last)) {
Now we go further and check whether the string is four to six characters long. using [[: Alpha:]] is a simple way to check that characters are not letters. The numbers in the curly braces check the number of characters. Also note that ^ and $ represent the beginning and end of the string, respectively.
if (!ereg ("^[[:alpha:]]{4,6}$", $first) | |!ereg ("^[[:alpha:]]{4,6}$", $last)) {
Finally, we construct a regular expression that verifies the validity of an e-mail address. The effect of this type of test has already sparked quite a lot of discussion. Nothing is perfect, but the procedure I have given below is very effective.
My baby program is derived from the PHP mail discussion group. That's a good place to go-see it often. Yes, the procedure looks a bit messy.
if (!ereg) (' ^[-!#$%& ' *+./0-9=? A-z^_ ' a-z{|} ~]+ '. ' @‘.‘ [-!#$%& ' *+/0-9=? A-z^_ ' a-z{|} ~]+.
' [-!#$%& ' *+./0-9=? A-z^_ ' a-z{|} ~]+$ ', $last)) {
Don't too much time to scrutinize this code, or first to the next page of content.
Iv. Simple method
What about the previous regular expressions? Interesting, isn't it? Would it be interesting to write a procedure in every program that needs to check an email address? Think about it, have to write so messy a program, but also have to write so many times! ... But, of course, there is a simpler way.
Remember the header file we learned before? It allows us to write a program, like the check procedure for this email address, and then include the program in multiple programs. In this way, if we want to rewrite this program, we just need to change one place and do not need to modify multiple files.
But to do this, we have to use a function.
We've used many times. Every time we query the database or check the length of the string, we use a function. These functions are from PHP. If you are an enthusiastic programmer, you can use the functions you have written to augment the functionality of PHP itself. But this part of the tutorial is a bit too advanced. The function we want to create is not the one, but the function written inside the PHP script.
A function is a piece of program code, we can pass one or more values to this code, and then this code will process the data we pass to it and return a value. Depending on the actual needs, functions can be simple or complex. But as long as we pass in a number, and then can get a number, you control it is complex or simple! This is the loveliness of the function.
The functions in PHP are similar to those in C. When we define a function, we must indicate what data the function needs to receive. It doesn't seem very good at first to understand why it has to receive data, but it can prevent some weird problems. The function can do this because the variables inside the function are private variables, that is, it exists only within the function.
For example, you have a variable called $myname in your program, and if you create a function, you want the function to use that $myname variable (the value is the same), that's not going to work. You can create a variable inside a function, called $myname, which can be used to get together, but with different values. But I don't recommend it! If you do, you may get confused when you wait six months to revise the program.
So we're going to create a function right now, just a simple one. We're going to give it a name and specify what variable it's going to receive. We have to define this function before we call this function.
<html>
<body>
<?php
function Addnum ($first, $second) {
$newnum = $first + $second;
return $newnum;
}
echo Addnum (4,5);
?>
</body>
</html>
That's fine! First, we created our own function. We define two new variables, $first and $second, and notice how they are defined. When calling this function, give the two variables a value of 4 assigned to the $first,5 in the order in which they appear. Then we simply add these two numbers together and return the results. "Back" here means sending the results back. In the final part of the program we show the number 9.
Let's create a function that will help a little bit with our database application. What about a function that handles errors properly? Try the following procedure:
<html>
<body>
<?php
function Do_error ($error) {
echo "Oh, it seems a bit of a problem ...<br>";
The error reported by Echo system is: $error. <br> ";
echo "It is best to temporarily close the Web site 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, try shutting down the MySQL database or using the wrong username or password. You will see a friendly, useful error message. A careful friend notices the @ symbol before the mysql_connect () function. It suppresses system error messages, allowing the program to get information about the error only from the Do_error () function. You'll also notice that we can pass a variable defined elsewhere as a parameter to a function, rather than assigning a value directly to the call. Remember I used a private variable for the function? That's not quite right. In fact, you can have the function access to variables outside the function. You might want to write a function that queries the database and then displays the results in multiple pages. You don't want to pass the database connection identity to the function every time. In this case, you can define the connection identity 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 very simple function, but it is important that you do not have to pass the WISHDB variable when you call this function-you can use the Word global to enable the function to access the variable. In this statement you can define multiple global variables separated by commas.
Finally, you can use optional parameters so that you seem to be a real expert. The key point here is that you specify a default value when you define a parameter in a function. Then, when you call this function, if you do not specify a different value for the parameter variable, the function automatically assigns the default value to the variable. If you specify a different value, the default value does not work.
Don't understand? For example, when you connect to a database, you are almost always connected to the same server and use the same username and password. Sometimes, however, you also need to connect to other servers. 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 you define a function, the variables used inside the function are defined as well. The first time this function is called, all parameter variables are the default values. On the second call, the server name changed, and the username and password did not change. That's great!
Think about where you can still use a function. You can use functions for data validation to perform commonly used functions, and so on. I use a lot of functions when I work with text that is displayed on a Web page. I can finish checking, parsing, and modifying the text at once, adding line breaks and HTML tags.
Now, the rest is my advice to you.
Advanced Skills
Talking about database development, we have a lot of things to learn. If you haven't learned how to design a database, and how to run the database reliably on different platforms, go and find a good book to read. This ability will bring you immeasurable benefits, in the long run, it will save you a lot of time and energy.
Also, seriously learn MySQL. This is a complex and interesting database with a lot of good documentation. The table structure, data type and SQL of the Learning database. If you have a real grasp of SQL, you can do quite a lot of actual work.
Finally, there is PHP. Almost everything you want can be found on the PHP Web site, including comprehensive documentation, discussion of mail discussion groups, program code base, and so on. An excellent way to learn about PHP is to study the examples given in the user's manual and look up the code on the Web. Users publish code that includes many functions and classes that you can use directly in your program without having to start over yourself. In addition, if you are having problems, the mail discussion group is a resource that is worth taking advantage of. PHP developers themselves will also participate in the mail discussion group, as well as many experienced experts, they can help you solve the problem.