Home > Articles > Data

From Database to Web Page: Four Easy Steps

These are the general steps you take to retrieve information from a database table and display it in a Web page:

  1. Open the database.

  2. Send an SQL command to the database to retrieve one or more records from a table(s) in the database.

  3. Display one or more fields from the records in a Web page.

  4. Close the database.

However, you can't take these steps in a plain-old HTML file. You need to combine HTML with a programming language, and this is where Active Server Pages (or ASP for short) comes in.

An ASP file is simply a text file, just like your HTML files are text files; the file extension for an ASP file is .asp versus .html or .htm for an HTML file. The key difference between an ASP file and an HTML file is that the typical ASP file contains both HTML and Visual Basic code. Whereas HTML "code" is delimited by angle brackets—otherwise known as "greater-than" and "less-than" signs—(< and >), Visual Basic code in an ASP file is delimited by the symbols <% and %> (commonly verbalized as "begin-percent" and "end-percent"). Once you create an ASP file, you upload it to the same Web server directory where you put your HTML files.

The best way to understand how to use ASP files to retrieve bootstrap content out of a database table and display it as a Web page is through an actual example. However, before doing this example, let's review the problem again, since there are so many different pieces to the solution—HTML, databases, Active Server Pages—that it's easy to forget exactly what problem we're trying to solve. Once you're comfortable with your understanding of both the problem and the solutions, it's a relatively straightforward matter to generalize the solution to bootstrap content on your own personal Web business site.

Review of the Problem

We have a database (hacker.mdb) and a table inside that database (hackerphrase) that contains about 50 hacker phrases. How do we get that information out of the database and onto a Web page so that a user can view it? First, let's look at the code (see Listing 1) that generates the home page for our hacker phrase site (refer to Figure 2).

Listing 1  The Script Without Active Server Pages Code

<HTML>
<HEAD>
<TITLE>Professor F's IT-Forum</TITLE>
<STYLE>
<!--
BODY {font-family:verdana,arial,helvetica;font-size:9pt}
TD   {font-family:verdana,arial,helvetica;font-size:9pt}
A    {color: #572119; font-weight: bold}
-->
</STYLE>
</HEAD>
<BODY>
<TABLE WIDTH=600 HEIGHT=400 CELLPADDING=0 CELLSPACING=0 BORDER=0>
<TR>
<TD WIDTH=120 VALIGN=TOP BGCOLOR=#DFCCAC>
  <img src=logo.gif><BR><BR>
<TABLE WIDTH=100%><TR><TD BGCOLOR=#572119 ALIGN=CENTER>
  <FONT COLOR=#DFCCAC><B>WORDAGE</B></FONT>
</TD></TR></TABLE>
  <A HREF=" ">Phrases</A><BR>
  <A HREF=" ">Dictionary</A><BR>
  <A HREF=" ">Archive</A><BR><BR>
<TABLE WIDTH=100%><TR><TD BGCOLOR=#572119 ALIGN=CENTER>
  <FONT COLOR=#DFCCAC><B>CULTURE</B></FONT>
</TD></TR></TABLE>
  <A HREF=" ">History</A><BR>
  <A HREF=" ">Definition</A><BR><BR>
<TABLE WIDTH=100%><TR><TD BGCOLOR=#572119 ALIGN=CENTER>
  <FONT COLOR=#DFCCAC><B>DISCUSSION</B></FONT>
</TD></TR></TABLE>
  <A HREF=" ">Forum</A><BR>
  <A HREF=" ">Chat</A>
</TD>
<TD WIDTH=480 VALIGN=TOP>
  <IMG src=informitad1.gif>
  <TABLE WIDTH=100% CELLPADDING=1 CELLSPACING=0 BORDER=0 HEIGHT=340>
  <TR>
    <TD WIDTH=360 VALIGN=TOP><BR>
      <CENTER><FONT STYLE="font-size:16pt" COLOR=#572119><B>
      Professor F's IT-Forum</B>
      </FONT></CENTER>
      <HR COLOR=#572119>
      <TABLE CELLSPACING=0 CELLPADDING=0 BORDER=0><TR>
      <TD BGCOLOR=LIGHTGREY>
      Welcome to <B>Professor F . com</B>--a repository of hacker
      culture and a forum for discussing I.T. issues. Our mission is
      to correct the negative, misportrayal of the hacker by the
      media. So, you won't find anything about breaking into
      computers on this site. Instead, you'll find something much
      more valuable--the truth. Enjoy!
      </TD></TR></TABLE>
      <HR COLOR=#572119><BR>
      <TABLE>
      <TR><TD VALIGN=TOP>Phrase</TD>
          <TD><B>Sure, you're bitter</B></TD></TR>
      <TR><TD VALIGN=TOP>Usage</TD>
          <TD>Whenever a friend or coworker complains too
              much.</TD></TR>
      <TR><TD VALIGN=TOP>Example</TD>
          <TD>Barney: I spend all night hacking this algorithm and
              I still can't get it to work<BR>
              Fred: Sure, you're bitter. </TD></TR>
      </TABLE>
    </TD>
    <TD WIDTH=120 VALIGN=TOP>
      <CENTER><FONT STYLE="font-size:12pt" COLOR=#572119><B>
        Top 5<BR>Phrases
      </CENTER></B></FONT>
      <TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=0 BORDER=1
             BGCOLOR=#DFCCAC BORDERCOLOR=#572119>
      <TR><TD>
        <TABLE>
        <TR><TD VALIGN=TOP>1.</TD><TD>Sure, you're bitter    </TD></TR>
        <TR><TD VALIGN=TOP>2.</TD><TD>Any other questions?   </TD></TR>
        <TR><TD VALIGN=TOP>3.</TD><TD>Help me Spock!         </TD></TR>
        <TR><TD VALIGN=TOP>4.</TD><TD>Are you threatening me?</TD></TR>
        <TR><TD VALIGN=TOP>5.</TD><TD>Did you just get in?   </TD></TR>
        </TABLE>
      </TD></TR></TABLE>
        <BR>
      <CENTER><FONT STYLE="font-size:12pt" COLOR=#572119><B>
      Top 5<BR>Words
      </CENTER></B></FONT>
      <TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=0 BORDER=1
             BGCOLOR=#DFCCAC BORDERCOLOR=#572119>
      <TR><TD>
        1. Foo<BR>
        2. Bar<BR>
        3. Baz<BR>
        4. Frob<BR>
        5. Grok
      </TD></TR></TABLE>
    </TD>
  </TR>
  </TABLE>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>

We need to replace the text highlighted in bold above with a phrase from our hackerphrase table. To solve this problem, we'll apply the four steps listed at the beginning of this section.

Step 1: Opening the Database in Active Server Pages

Opening a database in Active Server Pages (ASP) requires just two lines of code (see Listing 2). These two lines of code are the same for every ASP file you create for accessing a database. In the first line of code, you create a database object; for example, conn. Think of this database object as an intermediary between your ASP code and your database; that is, all communication with your database will take place via this database object. The database object needs to know which database to talk to, as you might have several databases on your Web site. So, in the second line of code (which I've had to split up into several lines for formatting reasons), you tell the database object which specific database to open—for this example, hacker.mdb.

Listing 2  Active Server Page Code to Open a Microsoft Access Database Called hacker.mdb

<%
'
' Line 1: Create the database object
'
set conn=server.createobject("ADODB.Connection")
'
' Line 2: Open a particular database (hacker.mdb)
'
conn.open("DBQ=" & server.mappath("hacker.mdb") & ";" & _
          "Driver={Microsoft Access Driver (*.mdb)};" )
%>
... remainder of listing same as Listing 1 ...

Now that our database is open, we can command it to retrieve content out of its tables. In the next section we'll write some code to retrieve a random hacker phrase out of the hackerphrase table.

Step 2: Send an SQL Command to Retrieve Records from a Table

Given a table that has records numbered from 1 to n, to randomly select a record you take the following steps:

  1. Count how many records are in the table.

  2. Select a particular record at random.

  3. Send a query to the database to retrieve that record.

To count how many records are in a table, you use the SQL SELECT query:

SELECT COUNT(*) AS variable FROM table

For example,

SELECT COUNT(*) AS np FROM hackerphrase

You then send this command to the database, using the database object's execute method (see Listing 3).

Listing 3  Code Fragment That Counts Records in a Table

set rs=conn.execute("SELECT COUNT(*) AS np FROM hackerphrase")

nphrases=rs("np")

We store the record returned by the query in a variable (arbitrarily labeled rs in this case). We then extract the total number of hacker phrases (np) from this record and store it in a variable, nphrases. Now that we know how many phrases are stored in the table, we can proceed to the second step of choosing a phrase at random. To accomplish this step, we use the built-in Visual Basic random functions (randomize and rnd) to help pick a number between 1 and the nphrases (see Listing 4):

Listing 4  Code Fragment to Randomly Choose a Phrase from the Table

randomize

n=CINT(rnd*nphrases+1)

Finally, we use another SQL SELECT query to grab that particular record (n):

SELECT * FROM table WHERE condition

For example,

SELECT * FROM hackerphrase WHERE phraseID=n

Again, you send this command to the database using the database object's execute method (see Listing 5):

Listing 5  Code Fragment to Retrieve the Randomly Selected Phrase

set rs=conn.execute("SELECT * FROM hackerphrase WHERE phraseID=" & n)

If we combine all these fragments, the code looks like Listing 6:

Listing 6  Combining Code Fragments to Retrieve a Random Record from the Database

<%
'
' Line 1: Create the database object
'
set conn=server.createobject("ADODB.Connection")
'
' Line 2: Open a particular database (hacker.mdb)
'
conn.open("DBQ=" & server.mappath("hacker.mdb") & ";" & _
          "Driver={Microsoft Access Driver (*.mdb)};" )
'
' Listing 3: Code fragment to count records in a table
'
set rs=conn.execute("SELECT COUNT(*) AS np FROM hackerphrase")
nphrases=rs("np")
'
' Listing 4: Code fragment to randomly choose a phrase from the table
'
randomize
n=CINT(rnd*nphrases+1)
'
' Listing 5: Code fragment to retrieve the randomly selected phrase
'
set rs=conn.execute("SELECT * FROM hackerphrase WHERE phraseID=" & n)
%>
... remainder of listing same as Listing 1 ...

Next, we'll display the hacker phrase in an HTML page. Refer to the bold items in Listing 1; what we want to do is substitute the phrase that we randomly selected from the database for those "hard-coded" bold items . The variable rs contains the record corresponding to that phrase. To replace the hard-coded phrases with fields from our randomly selected record, we use this syntax:

<%=recordvariable("fieldname")%>

Specifically, instead of the hard-coded hacker phrase (see Listing 7), you substitute the randomly selected hacker phrases (see Listing 8):

Listing 7  The Hard-Coded Hacker Phrase (Fragment of Listing 2)

...
      <TABLE>
      <TR><TD VALIGN=TOP>Phrase</TD>
          <TD><B>Sure, you're bitter</B></TD></TR>
      <TR><TD VALIGN=TOP>Usage</TD>
          <TD>Whenever a friend or coworker complains too
              much.</TD></TR>
      <TR><TD VALIGN=TOP>Example</TD>
          <TD>Barney: I spend all night hacking this algorithm and
              I still can't get it to work<BR>
              Fred: Sure, you're bitter. </TD></TR>
      </TABLE>
...

Listing 8  The Randomly Selected Hacker Phrase in Place

...
      <TABLE>
      <TR><TD VALIGN=TOP>Phrase</TD>
          <TD><B><%=rs("phrase")%>  </B></TD></TR>
      <TR><TD VALIGN=TOP>Usage</TD>
          <TD><%=rs("usage")%>
                   </TD></TR>
      <TR><TD VALIGN=TOP>Example</TD>
          <TD><%=rs("example")%>

                                         </TD></TR>
      </TABLE>
...

You then close the database (see the end of Listing 8 above). Listing 9 shows the final code, with ASP code highlighted.

Listing 9  Final ASP file to Randomly Select a Hacker Phrase from a Database

<%
set conn=server.createobject("ADODB.Connection")
conn.open("DBQ=" & server.mappath("hacker.mdb") & ";" & _

set rs=conn.execute("SELECT COUNT(*) AS np FROM hackerphrase")
nphrases=rs("np")

randomize
n=CINT(rnd*nphrases+1)

set rs=conn.execute("SELECT * FROM hackerphrase WHERE phraseID=" & n)
%>
<!--
1234567890123456789012345678901234567890123456789012345678901234567890
-->
<HTML>
<HEAD>
<TITLE>Professor F's IT-Forum</TITLE>
<STYLE>
<!--
BODY {font-family:verdana,arial,helvetica;font-size:9pt}
TD   {font-family:verdana,arial,helvetica;font-size:9pt}
A    {color: #572119; font-weight: bold}
-->
</STYLE>
</HEAD>
<BODY>
<TABLE WIDTH=600 HEIGHT=400 CELLPADDING=0 CELLSPACING=0 BORDER=0>
<TR>
<TD WIDTH=120 VALIGN=TOP BGCOLOR=#DFCCAC>
  <img src=logo.gif><BR><BR>
<TABLE WIDTH=100%><TR><TD BGCOLOR=#572119 ALIGN=CENTER>
  <FONT COLOR=#DFCCAC><B>WORDAGE</B></FONT>
</TD></TR></TABLE>
  <A HREF=" ">Phrases</A><BR>
  <A HREF=" ">Dictionary</A><BR>
  <A HREF=" ">Archive</A><BR><BR>
<TABLE WIDTH=100%><TR><TD BGCOLOR=#572119 ALIGN=CENTER>
  <FONT COLOR=#DFCCAC><B>CULTURE</B></FONT>
</TD></TR></TABLE>
  <A HREF=" ">History</A><BR>
  <A HREF=" ">Definition</A><BR><BR>
<TABLE WIDTH=100%><TR><TD BGCOLOR=#572119 ALIGN=CENTER>
  <FONT COLOR=#DFCCAC><B>DISCUSSION</B></FONT>
</TD></TR></TABLE>
  <A HREF=" ">Forum</A><BR>
  <A HREF=" ">Chat</A>
</TD>
<TD WIDTH=480 VALIGN=TOP>
  <IMG src=informitad1.gif>
  <TABLE WIDTH=100% CELLPADDING=1 CELLSPACING=0 BORDER=0 HEIGHT=340>
  <TR>
    <TD WIDTH=360 VALIGN=TOP><BR>
      <CENTER><FONT STYLE="font-size:16pt" COLOR=#572119><B>
      Professor F's IT-Forum</B>
      </FONT></CENTER>
      <HR COLOR=#572119>
      <TABLE CELLSPACING=0 CELLPADDING=0 BORDER=0><TR>
      <TD BGCOLOR=LIGHTGREY>
      Welcome to <B>Professor F . com</B>--a repository of hacker
      culture and a forum for discussing I.T. issues. Our mission is
      to correct the negative, misportrayal of the hacker by the
      media. So, you won't find anything about breaking into
      computers on this site. Instead, you'll find something much
      more valuable--the truth. Enjoy!
      </TD></TR></TABLE>
      <HR COLOR=#572119><BR>
      <TABLE>
      <TR><TD VALIGN=TOP>Phrase</TD>
          <TD><B><%=rs("phrase")%>  </B></TD></TR>
      <TR><TD VALIGN=TOP>Usage</TD>
          <TD><%=rs("usage")%>
                   </TD></TR>
      <TR><TD VALIGN=TOP>Example</TD>
          <TD><%=rs("example")%>

                                         </TD></TR>
      </TABLE>
    </TD>
    <TD WIDTH=120 VALIGN=TOP>
      <CENTER><FONT STYLE="font-size:12pt" COLOR=#572119><B>
        Top 5<BR>Phrases
      </CENTER></B></FONT>
      <TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=0 BORDER=1
             BGCOLOR=#DFCCAC BORDERCOLOR=#572119>
      <TR><TD>
        <TABLE>
        <TR><TD VALIGN=TOP>1.</TD><TD>Sure, you're bitter    </TD></TR>
        <TR><TD VALIGN=TOP>2.</TD><TD>Any other questions?   </TD></TR>
        <TR><TD VALIGN=TOP>3.</TD><TD>Help me Spock!         </TD></TR>
        <TR><TD VALIGN=TOP>4.</TD><TD>Are you threatening me?</TD></TR>
        <TR><TD VALIGN=TOP>5.</TD><TD>Did you just get in?   </TD></TR>
        </TABLE>
      </TD></TR></TABLE>
        <BR>
      <CENTER><FONT STYLE="font-size:12pt" COLOR=#572119><B>
      Top 5<BR>Words
      </CENTER></B></FONT>
      <TABLE WIDTH=100% CELLPADDING=0 CELLSPACING=0 BORDER=1
             BGCOLOR=#DFCCAC BORDERCOLOR=#572119>
      <TR><TD>
        1. Foo<BR>
        2. Bar<BR>
        3. Baz<BR>
        4. Frob<BR>
        5. Grok
      </TD></TR></TABLE>
    </TD>
  </TR>
  </TABLE>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
<%
rs.close
set rs=nothing
conn.close
set conn=nothing
%>

Our bootstrap is finished! I've uploaded a variation of Listing 9 to the hacker phrases Web site. Note that every time you load the home page or click the Hacker Sayings link, a new hacker phrase pops up. Next week we'll look at implementing the autonomous content link (see the dashed line in Figure 6). If you want to preview the material we'll cover in the next and future articles, go ahead and check out http://www.professorf.com. Meanwhile, your homework assignment is to implement a bootstrap for your personal Web business.

Figure 6 Autonomous content link (dashed line).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020