Using DBI in a Web application

Source: Internet
Author: User
Tags date empty header connect mysql sort sorted by name table name
web| programs So far, we have written dbi scripts for command interpreters in a command-line environment, but DBI is useful in other environments, such as in the development of web-based applications. When you write a DBI script that can be invoked from a Web browser, you open the new and interesting performance of interacting with the database.
For example, if you display data as a table, you can easily convert each column heading to a connection that you can select to reorder the data in that column. It allows you to view the data in different ways once you click it without having to type any queries. Or you can provide a standard format that a user can type for a database search, and then display
A page with search results. Such simple capabilities can specifically change the level of interactivity provided to access the content of the database. In addition, the ability of a Web browser to display is significantly better than that available in a terminal window, so the output often looks prettier.
In this section, we will create the following web-based script:
samp_db a common browser for tables in the database. This has nothing to do with any particular task that we want to accomplish with this database, but it illustrates several Web application design concepts and provides a convenient way to view the information contained in those tables.
Allows us to view the score browser for any given quiz or test score. It's handy as a quick way to review the results of a scoring event, and it's useful when we need to create a test-level curve, so we can mark the quiz with an alphabetical grade.
Find a script to share a History league member of common interest. Complete it by allowing the user to enter the search phrase, and then search for the phrase in the interests field of the member table. We've written a line command script to do this, but the web-based version provides a guiding reference point that allows you to compare two approaches to the same task.
We will use the CGI.PM Perl module to write these scripts, which is the easiest way to connect the DBI script to the Web (for instructions on obtaining the CGI.PM module, see Appendix A). The reason is called C G I. P m, because it helps to write a script that uses a common gateway protocol that defines how a Web server communicates with other programs. CGI.PM processing involves many of the task details of the general housekeeping process, such as collecting parameter values that are passed to the script as output through the Web server. CGI.PM also provides a convenient way to generate HTML output, which reduces the chance of writing unsightly HTML compared to writing your own original H T M tag.
In this chapter, you will learn enough about cgi.pm to write your own Web application, but certainly not all of the performance it includes. To learn more about this module, refer to "O fficial Guide to programming with CGI.PM", written by Lincoln Stein (published by John Wiley 1998), or consult the online documentation at the following Web site:
http://stein.cshl.org/www/software/CGI/

Apache to set CGI scripts

In addition to DBI and cgi.pm, writing web-based scripts requires more than one component: a Web server. The instructions here are for the Apache server to use the script, but if you want to adapt a little bit of these instructions, you can use a different server.
In general, the various parts of the Apache appliance are located in the/usr/local/apache directory. For our purposes, the most important subdirectories in this directory are H t d o C S (HTML document Tree), Cgi-bin (executable scripts and programs called by our B server), and C o n F (configuration file). These directories may also be placed elsewhere in the system. If so, make the appropriate adjustments to the following considerations.
You should verify that the Cgi-bin directory is not inside the Apache document tree so that the scripts inside it cannot be requested as unformatted text. It's a safe way to take precautions. You are also unwilling to allow malicious client programs to examine your scripts, and to extract the text of these scripts and study them as a security breach.
To install a CGI script that is used in Apache, place it in the Cgi-bin directory, and then change the ownership of the script to the user running Apache and change its schema to the executable and read-only mode for that user. For example, if Apache runs as a user named www, the following command is used:
% Chown www script_name
% chmod script_name
You may need to run these commands with www or root. If you do not allow the script to be installed in the Cgi-bin directory, you can request the system administrator to do so on your behalf.
After you install this script, you can request this script on your browser by sending the appropriate U R L to the Web server. The typical URL is this:
Http://your.host.name/cgi-bin/script_name
Requesting a script from a Web browser causes the Web server to execute it. Returns the output of the script, and the result appears in the browser as the We-B page.
If you are using a mod_perl CGI script for better performance, you can do this:
1 Ensure that there are at least the following versions of the required software: Perl 5.004, cgi.pm 2.36 and Mod_perl 1.07.
2 Ensure that the Mod_perl is compiled into Apache executable files.
3 Create a directory where the scripts are stored. I used the/usr/local/apache/cgi-perl. Cgi-bin should not reside within the Apache document tree, and the Cgi-perl directory should not be there for the same security reasons.
4 tells Apache to be associated with the script Mod_perl located in the Cgi-perl directory:

If you are using the current version of Apache, and this version uses a single configuration file, all of these instructions are placed in the httpd.conf. If the Apache version uses three old file methods to configure the information, the A L. s instruction is placed in the srm.conf and the location row is placed in the access.conf. For Cgi-perl directories, do not enable M o D, Perlsendheader, or perlsetupenv instructions. These are handled automatically by CGI.PM, and enabling them can result in conflict handling.
The URL of the Mod_perl script is similar to the URL of the standard CGI script. The only difference is that you specify Cgi-perl instead of Cgi-bin.
Http://your.host.name/cgi-perl/script_name
For more information, see the Mod_perl area of the Apache Web site at the following address:
http://perl.apache.org/

A brief introduction to CGI.PM

To write a Perl script that uses the CGI.PM module, place the use line near the beginning of the script, and then create a CGI object that lets you access the CGI.PM methods and variables:
Use CGI;
My ($cgi) =new CGI;
Our CGI script uses CGI.PM performance, which is implemented using the $CGI variable invocation method. For example, to generate a Level 1 title, we would use the H1 () method:
Print $cgi->h1 ("My Heading");
CGI.PM also supports the use of methods that allow functions to call it, without leading ' $ C g I-> '. I'm not using this syntax here because the ' $ C g I-> ' symbol is more akin to using DBI, because it prevents C g I. The P m function name conflicts with any function name that can be defined.
1. Check the input parameters and write the output
One of the things that CGI.PM does is look after all the ugly details, which involve collecting the input information provided by our B server to the script. To get that information, all you need to do is call the Param () method. You can get all the available parameter names as follows:
My (@param) = $cgi->param ();
To retrieve the value of a particular parameter, only the arguments that are of interest are named:

CGI.PM also provides output methods for generating delivery to client browsers. Consider the following HTML document:

This code uses $CGI to produce an equivalent document:


Use CGI.PM to generate output instead of writing your own original H T M L, some of the advantages of doing this are that they can be considered in logical units, rather than individual constituent identities, and that HTML is unlikely to contain errors (I say "unlikely" because CGI.PM does not forbid doing odd things, If it contains a column of internal headings). In addition, for
Written unlabeled text, CGI.PM provides automatic word escape, such as ' < ' and ' > ' as specified in HTML.
If you prefer, the use of the CGI.PM generation output method does not exclude the writing of your own original H T M L. You can mix the two methods together to invoke the CGI.PM method with the display statement that generates the text ID.
2. Escaped HTML and URL text
If you write unlabeled text by cgi.pm method, such as start_html () or H1 (), the specific characters in the text are automatically escaped. For example, if you use the following statement to generate a title, the ' & ' character in the title text will be made by C G I. P m converted to ' & A M P; ' :
Print $CGI->start_html (-title=> "a,b&c");
If you write unlabeled text without using CGI.PM to generate output, you might want to let it pass through escapehtml () to ensure that any specified characters are escaped correctly. This is also true when constructing URLs that may contain specific characters, although in that case you should use the Escape () method instead. It is important to use the appropriate encoding method because each method treats a different character set as a special character and treats a particular character encoding using a different format. Consider the following short Perl script:

If you run this script, it generates the following output, from which you can see that the encoding of the HTML text is different from the encoding of the URL:

3. Write a multi-purpose page
One of the main reasons for writing a web-based script to generate H T M, rather than writing static HTML documents, is that scripts can produce different types of pages, depending on how they are invoked. All of the CGI scripts we're going to write have this feature. Each one operates as follows:
1 when the script is first requested from the browser, it generates an initial page that allows you to select the type of information you want.
2 when the choice is made, the script is called again, but this time it is retrieved on the second page and displays the specific information requested.
The main problem here is that you want to determine the content of the second page from the selection of the first page, but usually the Web pages are independent of each other unless you arrange certain order of arrangement. The trick is to get the script to generate the page, which sets a value for the parameter, telling the script what the next call wants. When this script is first invoked, this parameter does not
value; tells the script to give it the initial page. When you point to the content of the information you want to see, the page calls the script again, but sets the argument to a value that indicates what the script does.
There are different ways to transfer instructions from the page back to the script. One way is to provide a form that a user fills out. When the user submits the form, it submits its contents to the Web server. The server passes information to the script, which, by invoking the Param () method, can find the content submitted. This is what we did with the third CGI script (allowing users to enter keywords for the search History League directory).
Another way to specify instructions for a script is to pass the information as part of the U R L sent to our B server when the script is requested. This is what we do with samp_db table browsers and fractional browser scripts. This works by scripting to generate pages that contain hyperlinks. Select a connection and call this script again, but this time
Specifies the value of the parameter, which indicates what the script does. In fact, the script calls itself in different ways to provide different types of results, depending on the connection the user chooses.
A script can allow you to call itself by sending a page with hyperlinks to its own URL to the browser. For example, a script my_script can write a page that contains the following connections:
<a href= "/cgi-bin/my_script" >click me!</a>
When the user typed the text "click me!" , the user's browser requests that the My_script be sent back to the Web server. Of course, all of this causes the script to send out the same page again because it doesn't support other information. However, if you attach a parameter to the URL, when the user selects the connection, it is sent back to the Web browser. Server
Calling this script, this script can invoke Param () to detect the parameters of the setting and act upon its value.
To attach the parameter to the end of the URL, add a "?" The character is placed in front of the name/value. To enclose multiple parameters, separate them with the character "&". For example:
/cgi-bin/my_script?name=value
/cgi-bin/my_script?name=value&name2=value2
To construct a self referenced u r l,c G I script with additional parameters, you should start by calling the Script_name () method to get your own u r L, and then add the parameters as follows:

After you construct U R L, you can generate a hyperlink <A> tag that includes it by using the cgi.pm A () method:
Print $cgi->a ({.href=> $url}, click me!);
It's easier to see how work can be done by checking a short CGI script. On the first call, the following script F L p _ f l o p gives a page called page A with a single hyperlink. Select this connection to call this script again, but set the page parameter and tell it to show page B. Page B also includes a connection to the script, but the page parameter has no value. Therefore, selecting this connection in page B causes the original page to be displayed again. The subsequent script call toggles the page back and forth between script A and script B:


If another client program appears and requests F L P _ f L o p, the initial page is given, because browsers for different clients do not interact with each other.
In fact, the value of the $url is set to a beautiful style by the previous sample. It is better to encode parameter names and values using the Escape () method after placing them behind a URL to avoid including special characters. Here's a good way to construct U R L with additional parameter values:


Connecting to a MySQL server from a Web script

We developed a command-line script in the previous section, "Run DBI," and shared a common text for the connection to the MySQL server. CGI scripts also share some of the code, but there are some differences:

This preceding article differs from the previous text used by command-line scripts in the following ways:
The first part now contains a use CGI statement.
The arguments for the command line are no longer parsed.
The code still looks for the connection parameters in the optional file, but does not use the. my.cnf file (also the home directory of the Web server user) in the home directory where the user executes the script. The WEB server may run scripts that access other databases, and there is no reason to assume that all scripts will use the same connection parameter. Instead, we look for alternative files that are stored in different locations (/US r/l o c a l/a p a c h e/c o n f/samp_db. C N F). If you want to use a different file, you should modify the path name of the optional file.
Scripts that are invoked through a Web server are used as Web server users, not as you run them. This raises a number of security issues because you are no longer in control after the Web server takes over. The ownership of the optional file should be given to the user running the Web server (possibly www or nobody or some similar user), and the mode is set to 4 0 0 or 6 0 0 so that other users cannot read it. Unfortunately, you can install this Web server script to execute anyone who is still able to read this file. All they have to do is write a script, open the optional file explicitly, and display its contents on the We b page. Because their scripts run as the We server user, it will have sufficient rights to read this file.
For this reason, it is prudent to create a MySQL user with read-only (S e L e C T) permissions on the samp_db database and then list the user's name and password in the samp_db.cnf file, rather than your own name and password. As a user who has the right to modify a database table, this does not risk allowing scripts to connect to the database. The 11th chapter, "Conventional MySQL Management," discusses how to create a MySQL user account with strict permissions.
Alternatively, you can schedule execution of the script under the Apache suexec mechanism. This allows a user who acts as a special permission to execute a script and then write a script to get the connection parameters from an optional file that is read-only for that user. For example, you might want to write a script that accesses a database.
Another way is to write a script that requests a user's name and password from a client user and uses these values to establish a connection to the MySQL server. This method is more appropriate for creating scripts for administrative purposes than for providing scripts for general use. In any case, some of the ways in which user names and password requests should be vigilant are attacked by some people who can
You can put a bug on the network between you and the server.
Because you can gather from the previous paragraphs, the security of web scripts is a tricky issue. Obviously, you should read a few more topics about security, because it's a big topic, so I can't really do it in a comprehensive way here. It's a good way to look at the information about security in the Apache manual. You can also find the WWW security FAQ saying
Ming, for example, you can use the following URL:
http://www.w3.org/Security/Faq/

samp_db Database Browser

For the first web-based application, we'll develop a simple script-samp_db-allows you to view the tables that exist in the SAMP_DB database and examine the contents of those tables interactively from a Web browser. SAMP_DB's working methods are as follows:
When you first request samp_db from a browser, it connects to the MySQL server, retrieves a list in the samp_db database, and sends a page to the browser, where each table appears as an optional connection. When you select a table name in this page, the 騑 EB server sends a request for Samp_browse to display the contents of that table.
When Samp_browse is invoked, if it receives a table name from the Web server, it retrieves the contents of the table and displays the information in a Web browser. The title of each column in the data is the name of the column in the table. The caption appears as a connection, and if one of them is selected, the browser sends a request to the Web server, displaying the same table, but sorting by the selected column.
Note that there is a warning: these tables in the SAMP_DB table are relatively small, so sending the entire contents of the table to the browser is not a big problem. If you edit samp_db to display tables in different databases that contain large tables, you should consider adding an L M i t clause to the row retrieval statement.
In the body of the Samp_browse script, we created the CGI object and canceled the initial part of the Web page. Then check to see if the specific tables are displayed according to our assumptions, based on the Tbl_name parameter values:

It's easy to figure out the value of the parameter, because CGI.PM does all the work of finding out what the Web server is passing to this script information. We simply invoke the Param () with the name of the parameter we are interested in, in the body of S a m P _ B R o S E, this parameter is tbl_name. If it is not defined or empty, it is the initial invocation of this script, and we display the table column. Otherwise, the contents of the table named by the Tbl_name parameter are displayed, sorted by the column values named by the Sort_column parameter. After displaying the appropriate information, we call end_html () to eliminate the end of the HTML flag.
The Display_table_list () function generates the initial page. Display_table_list () Retrieves the table column and writes out a single-column H T M L table that contains a database table name in each cell:


The page generated by Display_table_list () contains the following connections:

When Samp_browse is invoked, if the Tbl_name parameter has a value, the script passes that value to display_table (), along with the column name sorted by name. If there are no named columns, we sort by the first column (we can refer to the column by position, so it's easy to use the ORDER BY 1 clause to do it):

The table shows the pages of the column headings that are related to the connection to the table being displayed; These connections include sort _ c o l um n parameters, which explicitly specify the sorted columns. For example, for a page that displays the contents of an event table, the column header connection looks something like the following:

Display_table_list () and display_table () use the Display_cell (), the H T M L table as a function of the cell display value. This function uses a trick of converting a null value into an irreducible space (' & n b s p; Because empty cells do not display borders correctly in a table with borders. This problem is solved by placing an irreducible space in this unit. Display_cell () also has a third parameter that controls whether the cell value is encoded. This is required because the call to Display_cell () shows some of the cell values that have been encoded, such as column headings that contain URL information:

If you want to write more generic scripts, you can change the samp_browse to browse multiple databases. For example, at the beginning of a script, you can display a column of databases on a server, not a list in a particular database. Then, select a database, get a list of it, and continue from there.

Credits Save Scheme Score browser

Each time we enter a test score, we need to generate an ordered list of fractions to determine the level curve and assign the letter rank. Notice that all the things we will do with this list are displaying it so that we can determine where each letter level terminates. Then mark the level score on the test volume before returning to the student. We're not in the database.
Continue to record this letter level, because the rank at the end of the hierarchy cycle depends on the numeric score, not the letter level. Again, keep in mind that, strictly speaking, you should have a method of entering fractions before you can create a method for retrieving fractions. I'm going to save the input score script until the next chapter. During this period, in the database, we have been from the early stages of the hierarchy period
Got a few sets of points. We can use scripts with those fractions, even if there is no convenient way to score input.
Our script for browsing scores is somewhat similar to the samp_browse, but we want to see more specific goals for a given test or test score Score_browse. The initial page gives a list of possible level events from which to choose, allowing the user to select any of them to see the score associated with the event. The fractions of a given event are sorted by fractions in the order in which they were high, so that the results can be displayed and used to determine the rank curve.
Score _ B R O W s e only needs to check an argument e v e N T _ i d to see if a specific event is specified. If not, Score_browse displays the rows in the event table so that the user can select one of them. Otherwise, the score associated with the selected event is displayed:


Using the column name of the Request table column header, the function display_events () extracts the information from the event table and displays it in a tabular format. Inside each row, the event_id value is displayed as a connection that can be selected to trigger a query that retrieves the corresponding event score. The URL for each event is simply to the path with the additional parameter score _ B r O W s E, which specifies the event number:
/cgi-bin/score_browse?event_id=number
The display_events () function is written as follows:

When the user selects an event, the browser sends a SCORE_BROWSE request with an attached event ID value. Score_browse finds the event_id parameter set and calls Display_scores () to list the scores for all the specific events. This page also displays the text "Show Event List" As a connection back to the initial page so that users can easily return to the Event List page. The URL for this connection references the Score_browse script, but does not specify any value for the event_id parameter. The Display_scores () subroutine looks like this:

Display_scores () runs the query with our previous 1 in the 1th chapter. 4. The query developed in section 8, "Retrieving information from multiple Tables" section, describes how queries that write connections are extremely similar. In that chapter, we request a fraction of the given date because the date is more meaningful than the ID value of the event. Instead, when we use Score_browse, we know the exact event ID. That's not because we consider the event ID (we don't), but because the script gives us a list of event IDs that we can select from. You can see that this type of interface reduces the need to understand specific details. We don't have to know the ID of the event, we just need to identify the desired event.

Historical League search for common interest

Samp_browse and Score_browse scripts allow the user to make a choice by giving a list of choices on the initial page, and each selection in that page is a connection that invokes the script again with a specific parameter value. Another way to allow a user to make a choice is to place a table with editable fields on the page. This approach is more appropriate when the optional range is not constrained to a set of easily determined values. Our next script illustrates this method of requesting user input.
In the 7. In section 3, "Running DBI," we construct a command-line script for historical union members looking for shared specific interests. However, that script is not a script that the Federated member has already accessed; The Federated secretary must run the script and post the results to the member requesting the list. It is best to make this search more versatile so that members can use it on their own. Writing web scripts is one way to do this.
The script interests places a small number of tables where the user can enter the keyword, and then searches the member table for members who meet the criteria and displays the results. Perform this search by adding the wildcard "%" to both ends of the keyword so that it can be found anywhere in the interests column value.
A keyword table is displayed on each page so that users can enter new searches immediately, even on pages that display search results. In addition, the search string for the previous page is displayed in the keyword table so that if the user wants to run a similar search, you can edit the string. This eliminates the need to retype a lot of content:

Scripts and their exchange of information are slightly different from samp_browse or Score_browse. The interest parameter is not appended to the end of the URL, and the information in the table is encoded by the browser and sent out as part of the POST request. However, cgi.pm makes it irrelevant to send information, and parameter values are still obtained by calling Param ().
The function that implements the search and display results is shown below, and the function format_html_entry () for the formatted item is not displayed because it is the same as in the Gen_dir script:


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.