Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Tuesday, 9 June 2015

Create Login and Registration Form in PHP Using OOP

This article makes it easy to learn and use functions and sessions. Look at the following procedure.

Step 1
Create a database as in the following:
  1. Create database login_db;  
Step 2
Create a table as in the following:
  1. CREATE TABLE IF NOT EXISTS `users` (  
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `username` varchar(30) NOT NULL,  
  4.   `emailid` varchar(30) NOT NULL,  
  5.   `password` varchar(30) NOT NULL,  
  6.    PRIMARY KEY (`id`)  
  7. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;  
Step 3
Create a form named index.php as in the following:
  1. <!DOCTYPE html>  
  2.  <html lang="en" class="no-js">  
  3.  <head>  
  4.         <meta charset="UTF-8" />  
  5.         <title>Login and Registration Form with HTML5 and CSS3</title>  
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0">   
  7.         <meta name="description" content="Login and Registration Form with HTML5 and CSS3" />  
  8.         <meta name="keywords" content="html5, css3, form, switch, animation, :target, pseudo-class" />  
  9.         <meta name="author" content="Codrops" />  
  10.         <link rel="shortcut icon" href="../favicon.ico">   
  11.         <link rel="stylesheet" type="text/css" href="css/demo.css" />  
  12.         <link rel="stylesheet" type="text/css" href="css/style2.css" />  
  13.         <link rel="stylesheet" type="text/css" href="css/animate-custom.css" />  
  14.     </head>  
  15.     <body>  
  16.         <div class="container">  
  17.               
  18.               
  19.             <header>  
  20.                 <h1>Login and Registration Form  </h1>  
  21.             </header>  
  22.             <section>               
  23.                 <div id="container_demo" >  
  24.                      
  25.                     <a class="hiddenanchor" id="toregister"></a>  
  26.                     <a class="hiddenanchor" id="tologin"></a>  
  27.                     <div id="wrapper">  
  28.                         <div id="login" class="animate form">  
  29.                            <form name="login" method="post" action="">  
  30.                                 <h1>Log in</h1>   
  31.                                 <p>   
  32.                                     <label for="emailsignup" class="youmail" data-icon="e" > Your email</label>  
  33.                                     <input id="emailsignup" name="emailid" required="required" type="email" placeholder="mysupermail@mail.com"/>   
  34.                                 </p>  
  35.                                 <p>   
  36.                                     <label for="password" class="youpasswd" data-icon="p"> Your password </label>  
  37.                                     <input id="password" name="password" required="required" type="password" placeholder="eg. X8df!90EO" />   
  38.                                 </p>  
  39.                                 <p class="keeplogin">   
  40.                                     <input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />   
  41.                                     <label for="loginkeeping">Keep me logged in</label>  
  42.                                 </p>  
  43.                                 <p class="login button">   
  44.                                     <input type="submit" name="login" value="Login" />   
  45.                                 </p>  
  46.                                 <p class="change_link">  
  47.                                     Not a member yet ?  
  48.                                     <a href="#toregister" class="to_register">Join us</a>  
  49.                                 </p>  
  50.                             </form>  
  51.                         </div>  
  52.   
  53.                         <div id="register" class="animate form">  
  54.                             <form name="login" method="post" action="">  
  55.                                 <h1> Sign up </h1>   
  56.                                 <p>   
  57.                                     <label for="usernamesignup" class="uname" data-icon="u">Your username</label>  
  58.                                     <input id="usernamesignup" name="username" required="required" type="text" placeholder="mysuperusername690" />  
  59.                                 </p>  
  60.                                 <p>   
  61.                                     <label for="emailsignup" class="youmail" data-icon="e" > Your email</label>  
  62.                                     <input id="emailsignup" name="emailid" required="required" type="email" placeholder="mysupermail@mail.com"/>   
  63.                                 </p>  
  64.                                 <p>   
  65.                                     <label for="passwordsignup" class="youpasswd" data-icon="p">Your password </label>  
  66.                                     <input id="passwordsignup" name="password" required="required" type="password" placeholder="eg. X8df!90EO"/>  
  67.                                 </p>  
  68.                                 <p>   
  69.                                     <label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Please confirm your password </label>  
  70.                                     <input id="passwordsignup_confirm" name="confirm_password" required="required" type="password" placeholder="eg. X8df!90EO"/>  
  71.                                 </p>  
  72.                                 <p class="signin button">   
  73.                                     <input type="submit" name="register" value="Sign up"/>   
  74.                                 </p>  
  75.                                 <p class="change_link">    
  76.                                     Already a member ?  
  77.                                     <a href="#tologin" class="to_register"> Go and log in </a>  
  78.                                 </p>  
  79.                             </form>  
  80.                         </div>  
  81.                           
  82.                     </div>  
  83.                 </div>    
  84.             </section>  
  85.         </div>  
  86.     </body>  
  87. </html>  
Step 4
Create a config file named config.php as in the following:
  1. <?php  
  2.     define("DB_HOST", 'localhost');  
  3.     define("DB_USER", 'root');  
  4.     define("DB_PASSWORD", '');  
  5.     define("DB_DATABSE", 'mypratice');  
  6. ?>  
Step 5
Make a database connection class. Create the file named dbConnect.php as in the following:
  1. <?php  
  2.     class dbConnect {  
  3.         function __construct() {  
  4.             require_once('config.php');  
  5.             $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);  
  6.             mysql_select_db(DB_DATABSE, $conn);  
  7.             if(!$conn)// testing the connection  
  8.             {  
  9.                 die ("Cannot connect to the database");  
  10.             }   
  11.             return $conn;  
  12.         }  
  13.         public function Close(){  
  14.             mysql_close();  
  15.         }  
  16.     }  
  17. ?>  
Step 6
Make a Function class. Create the file named dbFunction.php as in the following:
  1. <?php  
  2. require_once 'dbConnect.php';  
  3. session_start();  
  4.     class dbFunction {  
  5.             
  6.         function __construct() {  
  7.               
  8.             // connecting to database  
  9.             $db = new dbConnect();;  
  10.                
  11.         }  
  12.         // destructor  
  13.         function __destruct() {  
  14.               
  15.         }  
  16.         public function UserRegister($username, $emailid, $password){  
  17.                 $password = md5($password);  
  18.                 $qr = mysql_query("INSERT INTO users(username, emailid, password) values('".$username."','".$emailid."','".$password."')") or die(mysql_error());  
  19.                 return $qr;  
  20.                
  21.         }  
  22.         public function Login($emailid, $password){  
  23.             $res = mysql_query("SELECT * FROM users WHERE emailid = '".$emailid."' AND password = '".md5($password)."'");  
  24.             $user_data = mysql_fetch_array($res);  
  25.             //print_r($user_data);  
  26.             $no_rows = mysql_num_rows($res);  
  27.               
  28.             if ($no_rows == 1)   
  29.             {  
  30.            
  31.                 $_SESSION['login'] = true;  
  32.                 $_SESSION['uid'] = $user_data['id'];  
  33.                 $_SESSION['username'] = $user_data['username'];  
  34.                 $_SESSION['email'] = $user_data['emailid'];  
  35.                 return TRUE;  
  36.             }  
  37.             else  
  38.             {  
  39.                 return FALSE;  
  40.             }  
  41.                
  42.                    
  43.         }  
  44.         public function isUserExist($emailid){  
  45.             $qr = mysql_query("SELECT * FROM users WHERE emailid = '".$emailid."'");  
  46.             echo $row = mysql_num_rows($qr);  
  47.             if($row > 0){  
  48.                 return true;  
  49.             } else {  
  50.                 return false;  
  51.             }  
  52.         }  
  53.     }  
  54. ?>  
Step 7
After the preceding procedure use the Function in index.php as in the following:
  1. <?php  
  2.     include_once('dbFunction.php');  
  3.        
  4.     $funObj = new dbFunction();  
  5.     if($_POST['login']){  
  6.         $emailid = $_POST['emailid'];  
  7.         $password = $_POST['password'];  
  8.         $user = $funObj->Login($emailid, $password);  
  9.         if ($user) {  
  10.             // Registration Success  
  11.            header("location:home.php");  
  12.         } else {  
  13.             // Registration Failed  
  14.             echo "<script>alert('Emailid / Password Not Match')</script>";  
  15.         }  
  16.     }  
  17.     if($_POST['register']){  
  18.         $username = $_POST['username'];  
  19.         $emailid = $_POST['emailid'];  
  20.         $password = $_POST['password'];  
  21.         $confirmPassword = $_POST['confirm_password'];  
  22.         if($password == $confirmPassword){  
  23.             $email = $funObj->isUserExist($emailid);  
  24.             if(!$email){  
  25.                 $register = $funObj->UserRegister($username, $emailid, $password);  
  26.                 if($register){  
  27.                      echo "<script>alert('Registration Successful')</script>";  
  28.                 }else{  
  29.                     echo "<script>alert('Registration Not Successful')</script>";  
  30.                 }  
  31.             } else {  
  32.                 echo "<script>alert('Email Already Exist')</script>";  
  33.             }  
  34.         } else {  
  35.             echo "<script>alert('Password Not Match')</script>";  
  36.           
  37.         }  
  38.     }  
  39. ?>  
  40. <!DOCTYPE html>  
  41.  <html lang="en" class="no-js">  
  42.  <head>  
  43.         <meta charset="UTF-8" />  
  44.         <title>Login and Registration Form with HTML5 and CSS3</title>  
  45.         <meta name="viewport" content="width=device-width, initial-scale=1.0">   
  46.         <meta name="description" content="Login and Registration Form with HTML5 and CSS3" />  
  47.         <meta name="keywords" content="html5, css3, form, switch, animation, :target, pseudo-class" />  
  48.         <meta name="author" content="Codrops" />  
  49.         <link rel="shortcut icon" href="../favicon.ico">   
  50.         <link rel="stylesheet" type="text/css" href="css/demo.css" />  
  51.         <link rel="stylesheet" type="text/css" href="css/style2.css" />  
  52.         <link rel="stylesheet" type="text/css" href="css/animate-custom.css" />  
  53.     </head>  
  54.     <body>  
  55.         <div class="container">  
  56.               
  57.               
  58.             <header>  
  59.                 <h1>Login and Registration Form  </h1>  
  60.             </header>  
  61.             <section>               
  62.                 <div id="container_demo" >  
  63.                      
  64.                     <a class="hiddenanchor" id="toregister"></a>  
  65.                     <a class="hiddenanchor" id="tologin"></a>  
  66.                     <div id="wrapper">  
  67.                         <div id="login" class="animate form">  
  68.                            <form name="login" method="post" action="">  
  69.                                 <h1>Log in</h1>   
  70.                                 <p>   
  71.                                     <label for="emailsignup" class="youmail" data-icon="e" > Your email</label>  
  72.                                     <input id="emailsignup" name="emailid" required="required" type="email" placeholder="mysupermail@mail.com"/>   
  73.                                 </p>  
  74.                                 <p>   
  75.                                     <label for="password" class="youpasswd" data-icon="p"> Your password </label>  
  76.                                     <input id="password" name="password" required="required" type="password" placeholder="eg. X8df!90EO" />   
  77.                                 </p>  
  78.                                 <p class="keeplogin">   
  79.                                     <input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />   
  80.                                     <label for="loginkeeping">Keep me logged in</label>  
  81.                                 </p>  
  82.                                 <p class="login button">   
  83.                                     <input type="submit" name="login" value="Login" />   
  84.                                 </p>  
  85.                                 <p class="change_link">  
  86.                                     Not a member yet ?  
  87.                                     <a href="#toregister" class="to_register">Join us</a>  
  88.                                 </p>  
  89.                             </form>  
  90.                         </div>  
  91.   
  92.                         <div id="register" class="animate form">  
  93.                             <form name="login" method="post" action="">  
  94.                                 <h1> Sign up </h1>   
  95.                                 <p>   
  96.                                     <label for="usernamesignup" class="uname" data-icon="u">Your username</label>  
  97.                                     <input id="usernamesignup" name="username" required="required" type="text" placeholder="mysuperusername690" />  
  98.                                 </p>  
  99.                                 <p>   
  100.                                     <label for="emailsignup" class="youmail" data-icon="e" > Your email</label>  
  101.                                     <input id="emailsignup" name="emailid" required="required" type="email" placeholder="mysupermail@mail.com"/>   
  102.                                 </p>  
  103.                                 <p>   
  104.                                     <label for="passwordsignup" class="youpasswd" data-icon="p">Your password </label>  
  105.                                     <input id="passwordsignup" name="password" required="required" type="password" placeholder="eg. X8df!90EO"/>  
  106.                                 </p>  
  107.                                 <p>   
  108.                                     <label for="passwordsignup_confirm" class="youpasswd" data-icon="p">Please confirm your password </label>  
  109.                                     <input id="passwordsignup_confirm" name="confirm_password" required="required" type="password" placeholder="eg. X8df!90EO"/>  
  110.                                 </p>  
  111.                                 <p class="signin button">   
  112.                                     <input type="submit" name="register" value="Sign up"/>   
  113.                                 </p>  
  114.                                 <p class="change_link">    
  115.                                     Already a member ?  
  116.                                     <a href="#tologin" class="to_register"> Go and log in </a>  
  117.                                 </p>  
  118.                             </form>  
  119.                         </div>  
  120.                           
  121.                     </div>  
  122.                 </div>    
  123.             </section>  
  124.         </div>  
  125.     </body>  
  126. </html>  
Step 8
Create a Home Page named home.php as in the following:
  1. <?php   
  2.     include_once('dbFunction.php');  
  3.     if($_POST['welcome']){  
  4.         // remove all session variables  
  5.         session_unset();   
  6.   
  7.         // destroy the session   
  8.         session_destroy();  
  9.     }  
  10.     if(!($_SESSION)){  
  11.         header("Location:index.php");  
  12.     }  
  13. ?>  
  14. <!DOCTYPE html>  
  15.  <html lang="en" class="no-js">  
  16.  <head>  
  17.         <meta charset="UTF-8" />  
  18.         <title>Login and Registration Form with HTML5 and CSS3</title>  
  19.         <meta name="viewport" content="width=device-width, initial-scale=1.0">   
  20.         <meta name="description" content="Login and Registration Form with HTML5 and CSS3" />  
  21.         <meta name="keywords" content="html5, css3, form, switch, animation, :target, pseudo-class" />  
  22.         <meta name="author" content="Codrops" />  
  23.         <link rel="shortcut icon" href="../favicon.ico">   
  24.         <link rel="stylesheet" type="text/css" href="css/demo.css" />  
  25.         <link rel="stylesheet" type="text/css" href="css/style2.css" />  
  26.         <link rel="stylesheet" type="text/css" href="css/animate-custom.css" />  
  27.     </head>  
  28.     <body>  
  29.         <div class="container">  
  30.               
  31.               
  32.             <header>  
  33.                 <h1>Welcome Form  </h1>  
  34.             </header>  
  35.             <section>               
  36.                 <div id="container_demo" >  
  37.                      
  38.                     <a class="hiddenanchor" id="toregister"></a>  
  39.                     <a class="hiddenanchor" id="tologin"></a>  
  40.                     <div id="wrapper">  
  41.                         <div id="login" class="animate form">  
  42.                            <form name="login" method="post" action="">  
  43.                                 <h1>Welcome </h1>   
  44.                                 <p>   
  45.                                     <label for="emailid" class="uname"   > Your Name </label>  
  46.                                    <?=$_SESSION['username']?>  
  47.                   
  48.                                 </p>  
  49.                                 <p>   
  50.                                     <label for="email" class="youpasswd"  > Your Email </label>  
  51.                                     <?=$_SESSION['email']?>  
  52.                                 </p>  
  53.                                    
  54.                                 <p class="login button">   
  55.                                     <input type="submit" name="welcome" value="Logout" />   
  56.                                 </p>  
  57.                                    
  58.                             </form>  
  59.                         </div>  
  60.   
  61.                           
  62.                     </div>  
  63.                 </div>    
  64.             </section>  
  65.         </div>  
  66.     </body>  
  67. </html>  
Step 9
After the preceding procedure has been done run your program. After running it the following wil be the output screens.

1- Login Screen

Login Screen

2- Registration Screen

Registration Screen

3- Home Screen 

Home Screen

Sunday, 22 March 2015

Introduction to Object Oriented Programming Concepts in C#


Introduction to Object Oriented Programming Concepts in C#

Introduction to Object Oriented Programming (OOP) concepts in C#: Abstraction, Encapsulation, Inheritance and Polymorphism.
OOP Features
Object Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic.

OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects.

  1. The software is divided into a number of small units called objects. The data and functions are built around these objects.
  2. The data of the objects can be accessed only by the functions associated with that object.
  3. The functions of one object can access the functions of another object.
OOP has the following important features.

 Class

A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages it is mandatory to create a class for representing data. 
A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data. 
A class will not occupy any memory space and hence it is only a logical representation of data.
To create a class, you simply use the keyword "class" followed by the class name:
class Employee
{

}

Object
Objects are the basic run-time entities of an object oriented system. They may represent a person, a place or any item that the program must handle.

"An object is a software bundle of related variable and methods."

"An object is an instance of a class"

oops-in-csharp.jpg 
A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object. 
When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory.
When an object is created without the new operator, memory will not be allocated in the heap, in other words an instance will not be created and the object in the stack contains the value null.
When an object contains null, then it is not possible to access the members of the class using that object.

class Employee
{

}

Syntax to create an object of class Employee:

Employee objEmp = new Employee();

All the programming languages supporting Object Oriented Programming will be supporting these three main concepts:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
Abstraction
Abstraction is "To represent the essential feature without representing the background details."

Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or objects by providing relevant information.

Abstraction is the process of hiding the working style of an object, and showing the information of an object in an understandable manner.

Real-world Example of Abstraction

Suppose you have an object Mobile Phone.

Suppose you have 3 mobile phones as in the following:

Nokia 1400 (Features: Calling, SMS)
Nokia 2700 (Features: Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)

Abstract information (necessary and common information) for the object "Mobile Phone" is that it makes a call to any number and can send SMS.

So that, for a mobile phone object you will have the abstract class as in the following:

   abstract class MobilePhone
    {
        public void Calling();
        public void SendSMS();
    }

    public class Nokia1400 : MobilePhone
    {
    }

    public class Nokia2700 : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
    }

    public class BlackBerry : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
        public void Recording();
        public void ReadAndSendEmails();
    }

Abstraction means putting all the variables and methods in a class that are necessary.
For example: Abstract class and abstract method.
Abstraction is a common thing.
Example
If somebody in your collage tells you to fill in an application form, you will provide your details, like name, address, date of birth, which semester, percentage you have etcetera.
If some doctor gives you an application to fill in the details, you will provide the details, like name, address, date of birth, blood group, height and weight.
See in the preceding example what is in common?
Age, name and address, so you can create a class that consists of the common data. That is called an abstract class. 
That class is not complete and it can be inherited by other classes.

Encapsulation

Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the property of encapsulating members and functions.

    class Bag
    {
        book;
        pen;
        ReadBook();
    }

Encapsulation means hiding the internal details of an object, in other words how an object does something.

Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.

Encapsulation is a technique used to protect the information in an object from another object.

Hide the data for security such as making the variables private, and expose the property to access the private data that will be public.

So, when you access the property you can validate the data and set it.

Example 1

    class Demo
    {
        private int _mark;

        public int Mark
        {
            get { return _mark; }
            set { if (_mark > 0) _mark = value; else _mark = 0; }
        }
    }

Real-world Example of Encapsulation
Let's use as an example Mobile Phones and Mobile Phone Manufacturers.
Suppose you are a Mobile Phone Manufacturer and you have designed and developed a Mobile Phone design (a class). Now by using machinery you are manufacturing Mobile Phones (objects) for selling, when you sell your Mobile Phone the user only learns how to use the Mobile Phone but not how the Mobile Phone works.

This means that you are creating the class with functions and by with objects (capsules) of which you are making available the functionality of your class by that object and without the interference in the original class.

Example 2

TV operation 
It is encapsulated with a cover and we can operate it with a remote and there is no need to open the TV to change the channel.
Here everything is private except the remote, so that anyone can access the remote to operate and change the things in the TV.

Inheritance

When a class includes a property of another class it is known as inheritance.
Inheritance is a process of object reusability.
For example, a child includes  the properties of its parents.
    public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine("Parent Constructor.");
        }

        public void print()
        {
            Console.WriteLine("I'm a Parent Class.");
        }
    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("Child Constructor.");
        }

        public static void Main()
        {
            ChildClass child = new ChildClass();

            child.print();
        }
    }

Output
    Parent Constructor.
    Child Constructor.
    I'm a Parent Class.

Polymorphism

Polymorphism means one name, many forms.
One function behaves in different forms.
In other words, "Many forms of a single object is called Polymorphism."

Real-world Example of Polymorphism

Example 1
A teacher behaves students.
A teacher behaves his/her seniors.
Here teacher is an object but the attitude is different in different situations.
Example 2
A person behaves the son in a house at the same time that the person behaves an employee in an office.
Example 3
Your mobile phone, one name but many forms:
  • As phone
  • As camera
  • As mp3 player
  • As radio
To read about Polmorphism in detail click the following link:

Polymorphism in .Net

The Differences between Abstraction and Encapsulation

AbstractionEncapsulation
1.  Abstraction solves the problem at the design level.1. Encapsulation solves the problem in the implementation level.
2. Abstraction hides unwanted data and provides relevant data.2. Encapsulation means hiding the code and data into a single unit to protect the data from the outside world.
3. Abstraction lets you focus on what the object does instead of how it does it3. Encapsulation means hiding the internal details or mechanics of how an object does something.
4. Abstraction: Outer layout, used in terms of design.
For example:
An external of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.
 
4. Encapsulation- Inner layout, used in terms of implementation.
For example: the internal details of a Mobile Phone, how the keypad button and display screen are connected with each other using circuits.
 
 The easier way to understand abstraction and encapsulation is as follows.
Real-world Example
Use an example of a Mobile Phone
You have a Mobile Phone, you can dial a number using keypad buttons. You don't even know how these are working internally. This is called Abstraction. You only have the information that is necessary to dial a number. But not internal working of the mobile.

But how does the Mobile Phone work internally? How are the keypad buttons connected with internal circuit? That is called Encapsulation.

Summary
"Encapsulation is accomplished using classes. Keeping data and methods that access that data into a single unit." 
"Abstraction is accomplished using an Interface. Just giving the abstract information about what it can do without specifying the details."
"Information/Data hiding is accomplished using modifiers by keeping the instance variables private or protected."

Wednesday, 25 February 2015

ADO Display

The most common way to display data from a recordset, is to display the data in an HTML table. 

Display the Field Names and Field Values

We have a database named "Northwind" and we want to display the data from the "Customers" table (remember to save the file with an .asp extension):

Example

<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT * FROM Customers", conn

do until rs.EOF
  for each x in rs.Fields
    Response.Write(x.name)
    Response.Write(" = ")
    Response.Write(x.value & "<br>")
  next
  Response.Write("<br>")
  rs.MoveNext
loop

rs.close
conn.close
%>

</body>
</html>


Display the Field Names and Field Values in an HTML Table

We can also display the data from the "Customers" table inside an HTML table with the following lines (remember to save the file with an .asp extension):

Example

<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
rs.Open "SELECT Companyname, Contactname FROM Customers", conn
%>

<table border="1" width="100%">
<%do until rs.EOF%>
  <tr>
  <%for each x in rs.Fields%>
    <td><%Response.Write(x.value)%></td>
  <%next
  rs.MoveNext%>
  </tr>
<%loop
rs.close
conn.close
%>
</table>

</body>
</html>


Add Headers to the HTML Table

We want to add headers to the HTML table to make it more readable (remember to save the file with an .asp extension):

Example

<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs = Server.CreateObject("ADODB.recordset")
sql="SELECT Companyname, Contactname FROM Customers"
rs.Open sql, conn
%>

<table border="1" width="100%">
  <tr>
  <%for each x in rs.Fields
    response.write("<th>" & x.name & "</th>")
  next%>
  </tr>
  <%do until rs.EOF%>
    <tr>
    <%for each x in rs.Fields%>
      <td><%Response.Write(x.value)%></td>
    <%next
    rs.MoveNext%>
    </tr>
  <%loop
  rs.close
  conn.close
  %>
</table>

</body>
</html>

ADO Recordset

To be able to read database data, the data must first be loaded into a recordset. 

Create an ADO Table Recordset

After an ADO Database Connection has been created, as demonstrated in the previous chapter, it is possible to create an ADO Recordset.  
Suppose we have a database named "Northwind", we can get access to the "Customers" table inside the database with the following lines:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Customers", conn
%>

Create an ADO SQL Recordset

We can also get access to the data in the "Customers" table using SQL:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
%>

Extract Data from the Recordset

After a recordset is opened, we can extract data from recordset.  
Suppose we have a database named "Northwind", we can get access to the "Customers" table inside the database with the following lines:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

set rs=Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn

for each x in rs.fields
  response.write(x.name)
  response.write(" = ")
  response.write(x.value)
next
%>

The ADO Recordset Object

The ADO Recordset object is used to hold a set of records from a database table. 

Introduction to ADO

What is ADO?

  • ADO is a Microsoft technology
  • ADO stands for ActiveX Data Objects
  • ADO is a Microsoft Active-X component
  • ADO is automatically installed with Microsoft IIS
  • ADO is a programming interface to access data in a database

Accessing a Database from an ASP Page

The common way to access a database from inside an ASP page is to:
  1. Create an ADO connection to a database
  2. Open the database connection
  3. Create an ADO recordset
  4. Open the recordset
  5. Extract the data you need from the recordset
  6. Close the recordset
  7. Close the connection
Before a database can be accessed from a web page, a database connection has to be established.

Create a DSN-less Database Connection

The easiest way to connect to a database is to use a DSN-less connection. A DSN-less connection can be used against any Microsoft Access database on your web site.
If you have a database called "northwind.mdb" located in a web directory like "c:/webdata/", you can connect to the database with the following ASP code:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
%>
Note, from the example above, that you have to specify the Microsoft Access database driver (Provider) and the physical path to the database on your computer.

Create an ODBC Database Connection

If you have an ODBC database called "northwind" you can connect to the database with the following ASP code:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Open "northwind"
%>
With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available.

An ODBC Connection to an MS Access Database

Here is how to create a connection to a MS Access Database: 
  1. Open the ODBC icon in your Control Panel.
  2. Choose the System DSN tab.
  3. Click on Add in the System DSN tab.
  4. Select the Microsoft Access Driver. Click Finish.
  5. In the next screen, click Select to locate the database.
  6. Give the database a Data Source Name (DSN).
  7. Click OK.
Note that this configuration has to be done on the computer where your web site is located. If you are running Personal Web Server (PWS) or Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to do this for you.