Sunday 6 May 2012

Make a Sign in form and store data in session

This tutorial tell you how to match username and password entered by user with stored records in database. Then store username in session variable. You can see sing up form here
You should follow these two points:
  1. Creat a database named 'olympic' and a table named 'user'.
    CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `postal_code` int(11) NOT NULL, `status` varchar(20) NOT NULL, `key` varchar(20) NOT NULL, `id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
  2. Copy and past code given below.
    <?php
    // Assigning value about your server to variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    $username=$_POST['username'];
    $password=$_POST['password'];

    $user_query="select * from user where username='$username'and password='$password'";

    $user_result=mysql_query($user_query);
    $user_row=mysql_fetch_array($user_result);
    $id=$user_row['id'];
    $num_user=mysql_num_rows($user_result);
    // Above query matches username and password entered by user with database records.
    if($num_user==1)
    {
    // if username and password exist in database assign username to session.
    // echo $_SESSION['username'] where you want to display username to user in you website
    $_SESSION['username'] = $user_row['username'];
    $_SESSION['id']=$id;
    // redirect user to home page or where you want
    header('Location: index.php');
    }
    else
    {
    echo "Invalid User Name or Password";
    }
    }
    ?>


    <form id='register' action='' method='post'>
    <fieldset >
    <legend>Register</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='username' >Username*: </label><br/>
    <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
    <label for='Password' >Password*:</label><br/>
    <input type='password' name='password' id='password' maxlength="50" /><br/>
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
    </form>

0 comments:

Post a Comment