CHAMPION KAY TUTORIAL

PHP Sessions


A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

PHP Session Variables

When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>

Pageviews=1

in the example below, we create a simple page-views counter. The isset() function checks if the "views" variable has already been set. If "views" has been set, we can increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:

<?php
session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:


<?php
unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.


PHP File Upload


Create an Upload-File Form

To allow users to upload files from a form can be very useful.
Look at the following HTML form for uploading files:

EXAMPLE:

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

Notice the following about the HTML form above:
  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.

Create The Upload Script

The "upload_file.php" file contains the code for uploading a file:

EXAMPLE:

<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?>

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:
  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload
This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

Restrictions on Upload

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb:

EXAMPLE:

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.

Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server.
The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:

EXAMPLE:

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

The script above checks if the file already exists, if it does not, it copies the file to the specified folder.
Note: This example saves the file to a new folder called "upload"





PHP Date() Function


The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.
 A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.

Syntax

date(format,timestamp)

Parameter            Description

  format                   Required. Specifies the format of the timestamp
 timestamp             Optional. Specifies a timestamp. Default is the current date and time


PHP Date() - Format the Date

The required format parameter in the date() function specifies how to format the date/time.
Here are some characters that can be used:
  • d - Represents the day of the month (01 to 31)
  • m - Represents a month (01 to 12)
  • Y - Represents a year (in four digits)
A list of all the characters that can be used in the format parameter, can be found in our PHP Date reference.
Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:

<?php
echo date("Y/m/d") . "<br />";
echo date("Y.m.d") . "<br />";
echo date("Y-m-d");
?>

The output of the code above could be something like this:

2009/05/11
2009.05.11
2009-05-11

PHP Date() - Adding a Timestamp

The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used.
The mktime() function returns the Unix timestamp for a date.
The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Syntax for mktime()


mktime(hour,minute,second,month,day,year,is_dst)

To go one day in the future we simply add one to the day argument of mktime():

<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>

The output of the code above could be something like this:

Tomorrow is 2009/05/12

Complete PHP Date Reference

For a complete reference of all date functions, go to our complete PHP Date Reference.
The reference contains a brief description, and examples of use, for each function!

PHP String Variables


String Variables in PHP

String variables are used for values that contain characters.
In this chapter we are going to look at the most common functions and operators used to manipulate strings in PHP.
After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable.
Below, the PHP script assigns the text "Hello World" to a string variable called $txt:

<?php
$txt="Hello World";
echo $txt;
?>

The output of the code above will be:

Now, lets try to use some different functions and operators to manipulate the string.

The Concatenation Operator

There is only one string operator in PHP.
The concatenation operator (.)  is used to put two string values together.
To concatenate two string variables together, use the concatenation operator:

<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings.

The strlen() function

The strlen() function is used to return the length of a string.
Let's find the length of a string:

<?php
echo strlen("Hello world!");
?>

The output of the code above will be:

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).

The strpos() function

The strpos() function is used to search for a character/text within a string.
If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:

<?php
echo strpos("Hello world!","world");
?>

The output of the code above will be:

6



PHP Variables


Variables in PHP

Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:

$var_name = value;

New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not work.
Let's try creating a variable containing a string, and a variable containing a number:

<?php
$txt="Hello World!";
$x=16;
?>

PHP is a Loosely Typed Language

In PHP, a variable does not need to be declared before adding a value to it.
In the example above, you see that you do not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
In PHP, the variable is declared automatically when you use it.

Naming Rules for Variables

  • A variable name must start with a letter or an underscore "_"
  • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
  • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)


PHP Syntax

Basic PHP Syntax

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form.

<?php
?>

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser:

<html>
<body>

<?php
echo "Hello World";
?>

</body>
</html>

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be executed.

Comments in PHP

In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

<html>
<body>

<?php
//This is a comment

/*
This is
a comment
block
*/
?>

</body>
</html>

PHP Installation


What do you Need?

If your server supports PHP you don't need to do anything.
Just create some .php files in your web directory, and the server will parse them for you. Because it is free, most web hosts offer PHP support.
However, if your server does not support PHP, you must install PHP.
Here is a link to a good tutorial from PHP.net on how to install PHP5:http://www.php.net/manual/en/install.php

Download PHP

Download PHP for free here: http://www.php.net/downloads.php

Download MySQL Database

Download MySQL for free here: http://www.mysql.com/downloads/

Download Apache Server

Download Apache for free here: http://httpd.apache.org/download.cgi

PHP Introduction


PHP is a server-side scripting language.

What You Should Already Know

Before you continue you should have a basic understanding of the following:
  • HTML/XHTML
  • JavaScript
If you want to study these subjects first, find the tutorials on our Home page.

What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a server-side scripting language, like ASP
  • PHP scripts are executed on the server
  • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
  • PHP is an open source software
  • PHP is free to download and use

What is a PHP File?

  • PHP files can contain text, HTML tags and scripts
  • PHP files are returned to the browser as plain HTML 
  • PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use

PHP + MySQL

  • PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP is FREE to download from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

Where to Start?

To get access to a web server with PHP support, you can:
  • Install Apache (or IIS) on your own server, install PHP, and MySQL
  • Or find a web hosting plan with PHP and MySQL support

Validation Server Controls

Validation Server Controls

A Validation server control is used to validate the data of an input control. If the data does not pass validation, it will display an error message to the user.
The syntax for creating a Validation server control is:

<asp:control_name id="some_id" runat="server" />

ASP.NET 2.0 - Navigation


Web Site Navigation

Maintaining the menu of a large web site is difficult and time consuming.
In ASP.NET 2.0 the menu can be stored in a file to make it easier to maintain. This file is normally called web.sitemap, and is stored in the root directory of the web.
In addition, ASP.NET 2.0 has three new navigation controls:
  • Dynamic menus
  • TreeViews
  • Site Map Path

The Sitemap File

The following sitemap file is used in this tutorial:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<siteMap>
  <siteMapNode title="Home" url="/aspnet/w3home.aspx">
    <siteMapNode title="Services" url="/aspnet/w3services.aspx">
      <siteMapNode title="Training" url="/aspnet/w3training.aspx"/>
      <siteMapNode title="Support" url="/aspnet/w3support.aspx"/>
    </siteMapNode>
  </siteMapNode>
</siteMap>

Rules for creating a sitemap file:
  • The XML file must contain a <siteMap> tag surrounding the content
  • The <siteMap> tag can only have one <siteMapNode> child node (the "home" page)
  • Each <siteMapNode> can have several child nodes (web pages)
  • Each <siteMapNode> has attributes defining page title and URL
lamp Note: The sitemap file must be placed in the root directory of the web and the URL attributes must be relative to the root directory.

Dynamic Menu

The <asp:Menu> control displays a standard site navigation menu.
Code Example:

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">
<asp:Menu runat="server" DataSourceId="nav1" />
</form>

The <asp:Menu> control in the example above is a placeholder for a server created navigation menu.
The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the  <asp:SiteMapDataSource> control.
The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).

TreeView

The <asp:TreeView> control displays a multi level navigation menu.
The menu looks like a tree with branches that can be opened or closed with + or - symbol.
Code Example:

<asp:SiteMapDataSource id="nav1" runat="server" />

<form runat="server">
<asp:TreeView runat="server" DataSourceId="nav1" />
</form>

The <asp:TreeView> control in the example above is a placeholder for a server created navigation menu.
The data source of the control is defined by the DataSourceId attribute. The id="nav1" connects it to the  <asp:SiteMapDataSource> control.
The <asp:SiteMapDataSource> control automatically connects to the default sitemap file (web.sitemap).

SiteMapPath

The SiteMapPath control displays the trail (navigation path) to the current page. The path acts as clickable links to previous pages.
Unlike the TreeView and Menu control the SiteMapPath control does NOT use a SiteMapDataSource. The SiteMapPath control uses the web.sitemap file by default.
lamp Tips: If the SiteMapPath displays incorrectly, most likely there is an URL error (typo) in the web.sitemap file.
Code Example:

<form runat="server">
<asp:SiteMapPath runat="server" />
</form>





ASP.NET 2.0 - Master Pages


Master Pages

Master pages allow you to create a consistent look and behavior for all the pages (or group of pages) in your web application.
A master page provides a template for other pages, with shared layout and functionality. The master page defines placeholders for the content, which can be overridden by content pages. The output result is a combination of the master page and the content page.
The content pages contains the content you want to display.
When users request the content page, ASP.NET merges the pages to produce output that combines the layout of the master page with the content of the content page.

Master Page Example


<%@ Master %>

<html>
<body>
<h1>Standard Header For All Pages</h1>
<asp:ContentPlaceHolder id="CPH1" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>

The master page above is a normal HTML page designed as a template for other pages.
The @ Master directive defines it as a master page.
The master page contains a placeholder tag <asp:ContentPlaceHolder> for individual content.
The id="CPH1" attribute identifies the placeholder, allowing many placeholders in the same master page.
This master page was saved with the name "master1.master".
lamp Note: The master page can also contain code, allowing dynamic content.

Content Page Example


<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">
  <h2>Individual Content</h2>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
</asp:Content>

The content page above is one of the individual content pages of the web.
The @ Page directive defines it as a standard content page.
The content page contains a content tag <asp:Content> with a reference to the master page (ContentPlaceHolderId="CPH1").
This content page was saved with the name "mypage1.aspx".
When the user requests this page, ASP.NET merges the content page with the master page.

Content Page With Controls



<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">
  <h2>W3Schools</h2>
  <form runat="server">
    <asp:TextBox id="textbox1" runat="server" />
    <asp:Button id="button1" runat="server" text="Button" />
  </form>
</asp:Content>

ASP.NET 2.0 - New Features


ASP.NET 2.0 improves ASP.NET by adding several new features.

Improvements in ASP.NET 2.0

ASP.NET 2.0 was designed to make web development easier and quicker.
Design goals for ASP.NET 2.0:
  • Increase productivity by removing 70% of the code
  • Use the same controls for all types of devices
  • Provide a faster and better web server platform
  • Simplify compilation and installation
  • Simplify the administration of web applications

What's New in ASP.NET 2.0?

Some of the new features in ASP.NET 2.0 are:
  • Master Pages, Themes, and Web Parts
  • Standard controls for navigation
  • Standard controls for security
  • Roles, personalization, and internationalization services
  • Improved and simplified data access controls
  • Full support for XML standards like, XHTML, XML, and WSDL
  • Improved compilation and deployment (installation)
  • Improved site management
  • New and improved development tools
The new features are described below.

Master Pages

ASP.NET didn't have a method for applying a consistent look and feel for a whole web site.
Master pages in ASP.NET 2.0 solves this problem.
A master page is a template for other pages, with shared layout and functionality. The master page defines placeholders for content pages. The result page is a combination (merge) of the master page and the content page.

Themes

Themes is another feature of ASP.NET 2.0. Themes, or skins, allow developers to create a customized look for web applications.
Design goals for ASP.NET 2.0 themes:
  • Make it simple to customize the appearance of a site
  • Allow themes to be applied to controls, pages, and entire sites
  • Allow all visual elements to be customized

Web Parts

ASP.NET 2.0 Web Parts can provide a consistent look for a site, while still allowing user customization of style and content.
New controls:
  • Zone controls - areas on a page where the content is consistent
  • Web part controls - content areas for each zone

Navigation

ASP.NET 2.0 has built-in navigation controls like
  • Site Maps
  • Dynamic HTML menus
  • Tree Views  

Security

Security is very important for protecting confidential and personal information.
In ASP.NET 2.0 the following controls has been added:
  • A Login control, which provides login functionality
  • A LoginStatus control, to control the login status
  • A LoginName control to display the current user name
  • A LoginView control, to provide different views depending on login status
  • A CreateUser wizard, to allow creation of user accounts
  • A PasswordRecovery control, to provide the "I forgot my password" functionality

Roles and Personalization

Internet communities are growing very popular.
ASP.NET 2.0 has personalization features for storing user details. This provides an easy way to customize user (and user group) properties.

Internationalization

Reaching people with different languages is important if you want to reach a larger audience.
ASP.NET 2.0 has improved support for multiple languages.

Data Access

Many web sites are data driven, using databases or XML files as data sources.
With ASP.NET this involved code, and often the same code had to be used over and over in different web pages.
A key goal of ASP.NET 2.0 was to ease the use of data sources.
ASP.NET 2.0 has new data controls, removing much of the need for programming and in-depth knowledge of data connections.

Mobility Support

The problem with Mobile devices is screen size and display capabilities.
In ASP.NET, the Microsoft Mobile Internet Toolkit (MMIT) provided this support.
In ASP.NET 2.0, MMIT is no longer needed because mobile support is built into all controls.

Images

ASP.NET 2.0 has new controls for handling images:
  • The ImageMap control - image map support
  • The DynamicImage control  - image support for different browsers
These controls are important for better image display on mobile devices, like hand-held computers and cell phones.

Automatic Compilation

ASP.NET 2.0 provides automatic compilation. All files within a directory will be compiled on the first run, including support for WSDL, and XSD files.

Compiled Deployment (Installation) and Source Protection

ASP.NET 2.0 also provides pre-compilation. An entire web site can be pre-compiled. This provides an easy way to deploy (upload to a server) compiled applications, and because only compiled files are deployed, the source code is protected.

Site Management

ASP.NET 2.0 has three new features for web site configuration and management:
  • New local management console
  • New programmable management functions (API)
  • New web-based management tool

Development Tools

With ASP.NET Visual Studio.NET was released with project and design features targeted at corporate developers.
With ASP.NET 2.0, Visual Studio 2005 was released.
Key design features for Visual Studio 2005 include:
  • Support for the features described above
  • Upload files from anywhere (FTP, File System, Front Page....)
  • No project files, allowing code to be manipulated outside Visual Studio
  • Integrated Web Site Administration Tool
  • No "build" step - ability to compile on first run
Visual Web Developer is a new free ASP.NET 2.0 tool for non-corporate developers who don't have 

ASP.NET - Database Connection

 What is ADO.NET?


1 ADO.NET is a part of the .NET Framework
2 ADO.NET consists of a set of classes used to handle data access
3 ADO.NET is entirely based on XML
4 ADO.NET has, unlike ADO, no Recordset object

Create a Database Connection

We are going to use the Northwind database in our examples.
First, import the "System.Data.OleDb" namespace. We need this namespace to work with Microsoft Access and other OLE DB database providers. We will create the connection to the database in the Page_Load subroutine. We create a dbconn variable as a new OleDbConnection class with a connection string which identifies the OLE DB provider and the location of the database. Then we open the database connection:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
sub Page_Load
dim dbconn
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
end sub
</script>

Create a Database Command

To specify the records to retrieve from the database, we will create a dbcomm variable as a new OleDbCommand class. The OleDbCommand class is for issuing SQL queries against database tables:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
sql="SELECT * FROM customers"
dbcomm=New OleDbCommand(sql,dbconn)
end sub
</script>

Create a DataReader

The OleDbDataReader class is used to read a stream of records from a data source. A DataReader is created by calling the ExecuteReader method of the OleDbCommand object:

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
sql="SELECT * FROM customers"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
end sub
</script>

Bind to a Repeater Control

Then we bind the DataReader to a Repeater control

<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
data source=" & server.mappath("northwind.mdb"))
dbconn.Open()
sql="SELECT * FROM customers"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>

<html>
<body>

<form runat="server">
<asp:Repeater id="customers" runat="server">

<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>Companyname</th>
<th>Contactname</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td><%#Container.DataItem("companyname")%></td>
<td><%#Container.DataItem("contactname")%></td>
<td><%#Container.DataItem("address")%></td>
<td><%#Container.DataItem("city")%></td>
</tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>

</asp:Repeater>
</form>

</body>
</html>

Close the Database Connection

Always close both the DataReader and database connection after access to the database is no longer required:

dbread.Close()
dbconn.Close()