Building a database-driven Web site with PHP and MySQL (v)

Source: Internet
Author: User
Tags format execution mysql variables php file php and php and mysql php code
mysql| Data | The database seems to be all right, but we're still not up to the point where we really interact with our users, and our users should be able to enter arbitrary information and hand it over to PHP for processing. Then our personalized Welcome page example, we want our users to arbitrarily enter his (or her) name and display it to the information, to let the user input data, we need to use HTML forms.

Here is the code for the form:


<form action= "welcome.php" method=get>
Name: <input type=text name= "FirstName" ><BR>
Last Name: <input type=text name= "LastName" >
<input type=submit value= "Go" >
</FORM>



Except where you can enter your name arbitrarily, the effect of this form is exactly the same as that of our second connection (using Firstname=kevin&lastname=yank in the query string). When you press the Submit button (marked "Go"), the browser loads the welcome.php and automatically adds the variables and their values to the query string. The variable name is the name attribute in the input type=text identity, and the value of the variable is the corresponding content entered by the user.

The method attribute in the INPUT type=text identity is used to tell the browser how to send the variable name and the value of the variable in the request. Get (which is what we use above) means passing variables in the query string, but there is another option. It is not always satisfying to display variables in the query string-sometimes technically impossible. If you include a TEXTAREA logo in your form that allows users to enter a large amount of text, this part of the text also appears to be too long in the query string and will exceed the maximum length of URLs that the browser can support. Another way to allow browsers to communicate information in a hidden manner. The code for this approach is almost the same as the code we see on the form above, except that we change the form's method from Get to post:


<form action= "welcome.php" method=post>
Name: <input type=text name= "FirstName" ><BR>
Last Name: <input type=text name= "LastName" >
<input type=submit value= "Go" >
</FORM>



This form is functionally identical to the one before us. The only difference is that the URL of the page loaded when the user presses the Go button does not have a query string. On the one hand, this allows you to submit a large amount of data or sensitive data (such as a password) through a form, rather than being displayed in a query string. On the other hand, if the user adds the resulting page from the Submit form to the Favorites folder, this favorite is not available because it does not contain the submitted data. Also, incidentally, search engines like AltaVista always use query strings to submit query criteria, mainly because they are designed to make it easier for users to add query results pages to favorites so that they can do the same search in the future because the search criteria are included in the URL.

Here is the basic principle of using forms to enable users to interact with PHP. In a future example, we'll discuss some of the more advanced issues and techniques.

Control statements

In the example of the PHP code we saw earlier, either there was only one single output text statement to the Web page, or a series of sequential statements. If you have written a program in another language, you should know that there are actually few such simple programs.

Like any other programming language, PHP provides a convenient way to handle the "control flow" in a script. That is, PHP contains special statements that you are not bound by the order in which they are executed sequentially. This statement is called a "control statement". Don't understand? Don't worry! There are some examples that will help you very well.

The most basic and commonly used control statement is the IF-ELSE statement. Its structure is this:


if (<condition>) {
If <condition> is true, the statement that will be executed.
} else {
(optional) If <condition> is false, the statement that will be executed.
}
The control language allows us to tell PHP which group of statements to execute according to the true and false of some conditions. If you don't think I'm a bit empty, we can change the welcome.php file we just created to:
if ($name = = "Kevin") {
Echo ("Welcome, OH Glorious leader!");
} else {
Echo ("Welcome, $name!");
}



Now, if the value of the name variable passed to this page is Kevin, a special message will be displayed. Otherwise, a generic message containing the entered name is displayed.

It is important to note that in this structure, the "Else clause" (which indicates what is executed when the condition is false in the IF-ELSE structure) is optional. For the above example, if our goal is to display special information when the appropriate name is entered, then nothing will be displayed. The code should be like this:


if ($name = = "Kevin") {
Echo ("Welcome, OH Glorious leader!");
}



The = = used in the above condition is the operator that compares two values for equality. The special note is that you need to enter two equal signs here. If you enter an equal sign and you actually use the assignment operator that we discussed earlier, you will no longer be comparing the values of the two variables, but assign a new value to the variable (this operation will return a true). The result of this is not only that the condition is always true, it can also change the value of the variable we want to examine, which can cause a lot of problems.

There is a safe way to prevent this error, which is to reverse the position of the variables and constants used to compare, as follows:

if ("Kevin" = $name) {


The effect is exactly the same, but when you forget the second equals sign, let's see what happens. PHP attempts to insert the value of a variable ($name) into a constant ("Kevin"). Because you can't change the value of a constant, PHP interrupts and prompts for an error message, which immediately prompts you to forget the second equals number!

Conditions can be more complex than whether a single comparison is equal. Recalling our modified welcome.php3, it is possible to acquire both FirstName and LastName at the same time. If we want to display a special message for a particular person, we can compare the two variables at the same time:


if ("Kevin" = $firstname and "yank" = = $lastname) {
Echo ("Welcome, OH Glorious leader!");
}



Only the value of $firstname is Kevin, and the $lastname value is yank when the condition returns TRUE. The meaning of an and is that when only two comparisons are true, the whole condition returns to true. There is also a symbol or, which makes the whole condition return true when at least one of the two comparisons is true. If you are in the JavaScript and C operators (&& and) and | | (or) are familiar, you can also use them in PHP as well.

Below we will see some more complex comparisons. Now, we just need to have a basic understanding of the If-else statement.

Another common PHP control statement is the while loop. The If-else statement allows us to choose whether or not to execute a set of statements based on criteria, while the while loop allows us to decide repeatedly how many times a set of statements can be executed based on criteria. The basic format of the while loop should be this:


while (<condition>) {
As long as <condition> is true, repeated execution of the statement
}



This is very much like a if-else statement without an ELSE clause. The difference is that when the statement finishes when the condition is true, it is no longer followed by the execution of the statement following The Terminator (}), but the condition is checked again. If this condition is still true. The statement will be executed repeatedly until the condition is no longer true. When this condition first returns false (regardless of the number of times it is checked), the statement following the execution loop (after the Terminator) is jumped.

Such loops can be used to handle a long list of things (such as jokes stored in a database), and here's a simple example: count to 10.


$count = 1;
while ($count <= 10) {
Echo ("$count");
$count + +;
}



I know this statement may seem scary, but we can look at it in a row. The first line defines a variable called $count and assigns it a value of 1. The second line is the start of the while loop, provided the $count is less than or equal to (<=) 10. The third and fourth rows are the loop bodies of the while loop, and we will execute it repeatedly when the condition is true. The third line simply prints out a $count value and adds a space to it thereafter. The $count value plus one ($count + + is the abbreviation for $count = $count + 1-The meaning of the two is exactly the same).

Now we can see how the program is implemented. When the condition is checked for the first time, the $count value is 1, so the condition is true. The value of the $count (1) is output, and then $count is given a new value of 2. When the condition is still true the second time the condition is checked, 2 is output and a new value of 3 is assigned. This process is continued, outputting 3, 4, 5, 6, 7, 8, 9 until 10. Finally, the $count is given a value of 11, the condition is false, and the loop ends. The final result is the output of such a string "1 2 3 4 5 6 7 8 9 10".

In the condition of this example we use a new operator: <= (less than or equal to). Other operators for numeric comparisons are >= (greater than or equal to),< (less than),> (greater than) and!= (not equal to). The last one can also be used in string comparisons.

Multi-purpose pages

If you want to display the visitor's name at the top of each page of the website you are building. Using our previous examples of automatic display of welcome information, we have basically succeeded in half. Now all we have to do is solve the problems with our example:

We need to be displayed on every page of the site, not just on one page.

We can't control which page on our site will be displayed first.

The solution to the first problem is not too difficult. When we get the user name variable on a page, we can pass this variable in any request by adding it to a query string:

<a href= "newpage.php?name=<?php Echo (UrlEncode ($name));?>" > A link </A>


Please note that we embed PHP code in the middle of the HTML identifier. In fact, this is very commonly used. We are already familiar with the Echo function, but we are not familiar with the UrlEncode function. The function of this function is to convert some special characters (such as spaces) in a string to a specific encoding so that they can be displayed in the query string. For example, if the value of the $name variable is "Kevin Yank", where the space is not allowed in the query string, the UrlEncode output will be Kevin+yank, and the value will be automatically converted back when the newpage.php is established in $name.

Ok, now you can pass the username to the first connection of our site. All we need now is to be able to get its value when it first appears. In our example above, we have done an HTML page to process the form that gets the user name. The problem is that we can't force users to start from this page every time they visit our site.

The solution is to check whether a username is specified on every page of our site, and if necessary, ask the user to enter a username. This means that every page on our site must be able to display the user name and prompt the user for input when no user name is specified. If you think about using the If-else statement now, that proves your ability to learn is really good!

Our "Multifunction page" should display completely different content according to different conditions, this page's source program will be like this:


<HTML>
<HEAD>
<TITLE> Multi-Purpose Page Outline </TITLE>
</HEAD>
<BODY>
<?php if (<condition>) {?>
<!--HTML content to display if <condition> is true-->
<?php} else {?>
<!--HTML content to display if <condition> is false-->
<?php}?>
</BODY>
</HTML>



The program initially looked messy, but in fact it was still a normal if-else statement, but it was inserted into the HTML code instead of the PHP statement we used earlier. This example illustrates one of the great advantages of PHP: You are free to choose when to proceed or exit "PHP mode." You can see <?php as a command to go into the "PHP mode" and see?> as a command to return to "normal HTML mode." So the example above becomes very easy to understand.

There is another format for the If-else statement, and using this format will make your program easier to read. If you use this format, the source program for our "multifunction page" will be like this:


<HTML>
<HEAD>
<TITLE> Multi-Purpose Page Outline </TITLE>
</HEAD>
<BODY>
<?php if (<condition>):?>
<!--HTML content to display if <condition> is true-->
<?php Else:?>
<!--HTML content to display if <condition> is false-->
<?php endif;?>
</BODY>
</HTML>



Ok, now that we have all the tools we need, let's take a look at a page in our site:


<HTML>
<HEAD>
<TITLE> Sample Page </TITLE>
</HEAD>
<BODY>
<?php if (isset ($name)):?>
<p>your Name: <?php Echo ($name);?></p>
<p>this paragraph contains a
<a href= "newpage.php?name=<?php echo" (UrlEncode
($name)); ?> ">link</A> that passes the
Name variable on to the next document.</p>
<?php Else:?>
<!--No name has been provided, so we
Prompt the user for one. -->
<form action=<?php Echo ($PHP _self);?> method=get>
Please enter your name: <input type=text name= "Name" >
<input type=submit value= "Go" >
</FORM>
<?php endif;?>
</BODY>
</HTML>



There are two new things in the above program, but it shouldn't be too difficult to understand them. First, we used a new function in the condition: isset. The function returns (output) a logical false when the variable has been assigned (in our case the user name is provided), and it will return (out) a logical truth; when the variable is not assigned (in our case, the username is not provided), the function returns (outputs) a logic fake. The second new thing is to use the $php_self variable in the action attribute in the specified form flag. This variable is one of the automatically generated system variables. Specifically, $PHP _self is always set to the URL of the current page. This provides a simple way to do this when a form points to the same page at the time of submission. Only then the $name variable has already been assigned a value.

After you add this section to all the pages on your site, you will be prompted to enter the username no matter what page the visitor is visiting for the first time. You can reach the page they really want to visit only if you enter a username and press go. The user name you enter is passed to each subsequent page through the query string in each connection, ensuring that only visitors are required to enter the user name once.

Conclusion

In this chapter, we introduce all of PHP's basic syntax: statements, variables, operators, and control statements. Our example is very simple. But in fact PHP's powerful function is its built-in hundreds of functions, using these functions you can access the data in the MySQL database to send mail, you can create a dynamic image to build a PDF file, you can do many other things.

In the fourth chapter, we will explore the use of MySQL on the web to publish the joke database we built in the previous chapter!



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.