1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

how to create registration form?

Discussion in 'PHP' started by hellz_guy, Jun 19, 2013.

  1. #1
    i am new at php and m trying to create registration form for my trial website i do have form table but dont have any idea to connect, so i need some idea about it.
     
    Solved! View solution.
    hellz_guy, Jun 19, 2013 IP
  2. ActiveFrost

    ActiveFrost Notable Member

    Messages:
    2,072
    Likes Received:
    63
    Best Answers:
    3
    Trophy Points:
    245
  3. robinton

    robinton Member

    Messages:
    44
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    33
    #3
    1. This is a simple tutorial that will teach you on how to create a simple registration form using (PHP/MySQL with JavaScript for input validation. This tutorial will not teach you on how to create a good design but rather to give you knowledge on how to create a fully functional registration form.
      Creating our Table

      First we are going to create our database which stores our data.
      To create a database:
      1. Open (phpmyadmin)
      2. Click create table and name it as simple_login.
      3. Then name the database as "simple_login".
      4. After creating a database name, click the SQL and paste the below code.
    CREATE TABLE IF NOT EXISTS `member` (
     
    `mem_id` int(11) NOT NULL AUTO_INCREMENT,
     
    `username` varchar(30) NOT NULL,
     
    `password` varchar(30) NOT NULL,
     
    `fname` varchar(30) NOT NULL,
     
    `lname` varchar(30) NOT NULL,
     
    `address` varchar(100) NOT NULL,
     
    `contact` varchar(30) NOT NULL,
     
    `picture` varchar(100) NOT NULL,
     
    `gender` varchar(10) NOT NULL,
     
    PRIMARY KEY (`mem_id`)
     
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
    Code (markup):
    Creating The Form


    Next step is to create a form and save it as index.php. To create a form, open your HTML code editor and paste the code below after the tag.

    Creating our Connection
        <form name="reg" action="code_exec.php" onsubmit="return validateForm()" method="post">
        <table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
        <tr>
        <td colspan="2">
        <div align="center">
        <?php
        $remarks=$_GET['remarks'];
        if ($remarks==null and $remarks=="")
        {
        echo 'Register Here';
        }
        if ($remarks=='success')
        {
        echo 'Registration Success';
        }
        ?>
        </div></td>
        </tr>
        <tr>
        <td width="95"><div align="right">First Name:</div></td>
        <td width="171"><input type="text" name="fname" /></td>
        </tr>
        <tr>
        <td><div align="right">Last Name:</div></td>
        <td><input type="text" name="lname" /></td>
        </tr>
        <tr>
        <td><div align="right">Gender:</div></td>
        <td><input type="text" name="mname" /></td>
        </tr>
        <tr>
        <td><div align="right">Address:</div></td>
        <td><input type="text" name="address" /></td>
        </tr>
        <tr>
        <td><div align="right">Contact No.:</div></td>
        <td><input type="text" name="contact" /></td>
        </tr>
        <tr>
        <td><div align="right">Picture:</div></td>
        <td><input type="text" name="pic" /></td>
        </tr>
        <tr>
        <td><div align="right">Username:</div></td>
        <td><input type="text" name="username" /></td>
        </tr>
        <tr>
        <td><div align="right">Password:</div></td>
        <td><input type="text" name="password" /></td>
        </tr>
        <tr>
        <td><div align="right"></div></td>
        <td><input name="submit" type="submit" value="Submit" /></td>
        </tr>
        </table>
        </form>
    Code (markup):
    Next step is to create a database connection and save it as "connection.php". This file is used to connect our form to database. This file serves as a bridge between our form and our database.

    <?php
    $mysql_hostname = "localhost";
    $mysql_user = "root";
    $mysql_password = "";
    $mysql_database = "registration";
    $prefix = "";
    $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
    mysql_select_db($mysql_database, $bd) or die("Could not select database");
    ?>
    PHP:
    Writing Our Save Script


    Next step is to create our script that save our input data to database and save it as code_exec.php.
    <?php
     
            session_start();
        include('connection.php');
        $fname=$_POST['fname'];
        $lname=$_POST['lname'];
        $mname=$_POST['mname'];
        $address=$_POST['address'];
        $contact=$_POST['contact'];
        $pic=$_POST['pic'];
        $username=$_POST['username'];
        $password=$_POST['password'];
        mysql_query("INSERT INTO member(fname, lname, gender, address, contact, picture, username, password)VALUES('$fname', '$lname', '$mname', '$address', '$contact', '$pic', '$username', '$password')");
        header("location: index.php?remarks=success");
        mysql_close($con);
        ?>
    PHP:
    Validating The Input


    To add some input validation using javascript, add the code below in the head tag of your index.php file. Input validation is used to make sure that all input field are filled out before saving the to database.
    <script type="text/javascript">
     
    function validateForm()
     
    {
     
    var a=document.forms["reg"]["fname"].value;
     
    var b=document.forms["reg"]["lname"].value;
     
    var c=document.forms["reg"]["mname"].value;
     
    var d=document.forms["reg"]["address"].value;
     
    var e=document.forms["reg"]["contact"].value;
     
    var f=document.forms["reg"]["pic"].value;
     
    var g=document.forms["reg"]["pic"].value;
     
    var h=document.forms["reg"]["pic"].value;
     
    if ((a==null || a=="") && (b==null || b=="") && (c==null || c=="") && (d==null || d=="") && (e==null || e=="") && (f==null || f==""))
     
    {
     
    alert("All Field must be filled out");
     
    return false;
     
    }
     
    if (a==null || a=="")
     
    {
     
    alert("First name must be filled out");
     
    return false;
     
    }
     
    if (b==null || b=="")
     
    {
     
    alert("Last name must be filled out");
     
    return false;
     
    }
     
    if (c==null || c=="")
     
    {
     
    alert("Gender name must be filled out");
     
    return false;
     
    }
     
    if (d==null || d=="")
     
    {
     
    alert("address must be filled out");
     
    return false;
     
    }
     
    if (e==null || e=="")
     
    {
     
    alert("contact must be filled out");
     
    return false;
     
    }
     
    if (f==null || f=="")
     
    {
     
    alert("picture must be filled out");
     
    return false;
     
    }
     
    if (g==null || g=="")
     
    {
     
    alert("username must be filled out");
     
    return false;
     
    }
     
    if (h==null || h=="")
     
    {
     
    alert("password must be filled out");
     
    return false;
     
    }
     
    }
     
    </script>
    Code (markup):
     
    Last edited by a moderator: Jun 26, 2013
    robinton, Jun 20, 2013 IP
  4. D3Tek

    D3Tek Active Member

    Messages:
    164
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    50
    #4
    robinton, that registration script is RIDDLED with security flaws! Not to mention the outdated technology.
     
    D3Tek, Jun 20, 2013 IP
    ryan_uk likes this.
  5. Strider64

    Strider64 Member

    Messages:
    40
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    25
    #5
    Here's a little more up-to-date one:

    <?php
    //Start session       
    session_start();   
    // create an user $_SESSION array:
    $_SESSION['user'] = NULL;
    // Set error message to Null
    $errMsg = NULL;       
    // Create the database connection as a PDO object:
    try {
     
        $db_options = array(
                      // important! use actual prepared statements (default: emulate prepared statements)
              PDO::ATTR_EMULATE_PREPARES => false                   
              , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION          // throw exceptions on errors (default: stay silent)
              , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC      // fetch associative arrays (default: mixed arrays)
          );         
     
        $pdo = new PDO('mysql:host=localhost;dbname=demo_login_system;charset=utf8', 'your_username', 'your_password', $db_options);   
     
    } catch (PDOException $e) { // Report the Error!
     
        $errMsg = "<p>Something is not right, check your php.ini settings or code</p>";
     
    }       
     
    // A nice little function that sanitizes the data output:
    function html_escape($raw_input) {
      return htmlspecialchars($raw_input, ENT_QUOTES | ENT_HTML401, 'UTF-8');    // important! don't forget to specify ENT_QUOTES and the correct encoding
    }      
    PHP:
    <?php
    /*
        ********* TABLE Structure *********
        CREATE TABLE IF NOT EXISTS `users` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `username` varchar(30) NOT NULL,
          `password` char(60) NOT NULL,
          `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
    */
     
    // common.inc.php file contains required
    // database connection  & initialization info:
    require 'includes/common.inc.php';
     
    // A nice password hashing library for PHP 5
    // Find it here: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
    // Read the Documentation for further help:
    // NOTE: if you're not using PHP 5, there are plenty of
    // other good password hashing libraries out there ---> JUST GOOGLE IT!
    require 'includes/password.inc.php';
     
     
    // Check to see if user has submitted form:
    if (isset($_POST['action']) && $_POST['action'] == 'register') {
     
        // Grab the user's input from form: 
        $username = $_POST['username'];
        $password = $_POST['password'];
     
        // Using Regex to check username:
        if (preg_match("/^[0-9a-zA-Z_]{5,}$/", $username) === 0) {
            $errMsg = '<p>Username must be bigger that 5 chars and contain only digits, letters and underscore<p>';
        }
     
        // Using Regex to check password:
        if (preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $password) === 0) {
            $errMsg .= '<p>Password must be at least 8 characters, and must contain at least one lower case letter, one upper case letter and one digit.</p>';       
        }
     
        // Function to check if username is available:
        function isUsernameAvailable($username, $pdo) {   
     
            // The PDO Query: 
            $query = "
                SELECT
                    1
                FROM users
                WHERE
                    username = :username1
            ";
     
            // The prepared property/attribute:
            $query_params = array(
                ':username1' => $username
            );   
     
            // These two statements run the query against your database table.
            $stmt = $pdo->prepare($query);
            $result = $stmt->execute($query_params);
     
            // The fetch() method returns an array representing the "next" row from
            // the selected results, or false if there are no more rows to fetch.             
            return $row = $stmt->fetch();     
            // If a row was returned, then we know a matching username was found in
            // the database already and we should return a boolean value back.     
     
        }
     
        // Check to see if username is available:
        $result = isUsernameAvailable($username, $pdo);
     
        // If username is taken then assign to $errMsg:
        if ($result) {
            $errMsg .= '<p>Username: ' . $username . ' is already taken.</p>';           
        }
     
        // Hash the password - See above for details:   
        $password = password_hash($password, PASSWORD_BCRYPT, array("cost" => 15));   
     
        // Store user's credentials, if form data is validated:
        if(!$errMsg) {
          // Using prepared statements:                 
          $query = 'INSERT INTO users ( username, password ) VALUES ( :username, :password )';
          $stmt = $pdo->prepare($query);
          $result = $stmt->execute(array(':username' => $username, ':password' => $password));           
          $errMsg = 'You have successfully registered to our great website!';                   
        }     
     
    }
    ?>
    <!--/Display Errors if there are any - using a ternary operator-->
    <?php echo (isset($errMsg)) ? $errMsg : '<h1>Registration Page</h1>'; ?>
     
    <form action="register.php" method="post"/>
     
    <input type="hidden" name="action" value="register" />
     
    Username: <input type="text" name="username"/><br />
    Password: <input type="password" name="password"/><br />
    <input type="submit" value="register!"/>
    </form>
    PHP:
    <?php
    // common.inc.php file contains required
    // database connection initialization info:
    require 'includes/common.inc.php';
     
    // A nice password hashing library for PHP 5
    // Find it here: https://github.com/ircmaxell/password_compat/blob/master/lib/password.php
    // Read the Documentation for further help:
    require 'includes/password.inc.php';
     
    if (isset($_POST['action']) && $_POST['action'] == 'login') {
     
        // This query retreives the user's information from the database using
        // their username.
        $query = '
                SELECT
                    id,
                    username,
                    password,
                    DATE_FORMAT(date_added, "%e %M %Y") as date_added
                FROM users
                WHERE
                    username = :username
                ';
     
        // The parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );       
     
     
        try
        {
            // Execute the query against the database
            $stmt = $pdo->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
     
        // This variable tells us whether the user has successfully logged in or not.
        // We initialize it to false, assuming they have not.
        // If we determine that they have entered the right details, then we switch it to true.
        $login_ok = false;       
     
        // Retrieve the user data from the database.  If $row is false, then the username
        // they entered is not registered.
        $row = $stmt->fetch();
     
        if($row)
        {
            // Verify Stored Hashed Password:
            $result = password_verify($_POST['password'], $row['password']);
     
            if ($result) {
                $login_ok = true;   
            } else {
                $errMsg = '<p>Your credientials do not match!</p>';
            }
     
        }
     
        // If login is OK:
        if ($login_ok) {
     
            // It's not wise to store the password in $_SESSION:
            unset($row['password']);   
     
            // This stores the user's data into the session at the index 'user'.
            // We will check this index on the private members-only page to determine whether
            // or not the user is logged in.  We can also use it to retrieve
            // the user's details.
            $_SESSION['user'] = $row;
     
            // The following output is just to prove that it works:
            echo '<pre>';
            print_r($_SESSION);
            echo '</pre>';
     
            // Redirect the user to the private members-only page.
            //header("Location: admin.php");
            //die("Redirecting to: admin.php");       
        }
     
    }
    /*
    *  This was just to help people who are just getting started
    *  learning how to program in the PHP Language. The PDO portion
    *  is written in Object-Oriented Style, but this doesn't mean
    *  that you now know OOP or that you have to use it. It's pretty
    *  straight forward in my opinion. I have tested this out, but I make
    *  no guarantees that it works 100 percent and it diffentely needs
    *  updating/styling. However, that is up to you and besides it's
    *  a good way to learn PHP. 
    */
    ?>
     
    <!--/Display Errors if there are any - using a ternary operator-->
    <?php echo (isset($errMsg)) ? $errMsg : '<h1>Login Page:</h1>'; ?>
     
    <form action="login.php" method="post"/>
     
    <input type="hidden" name="action" value="login" />
     
    Username: <input type="text" name="username"/><br />
    Password: <input type="password" name="password"/><br />
    <input type="submit" value="submit"/>
    </form>
    
    PHP:
     
    Strider64, Jun 20, 2013 IP
    sarahk, ryan_uk and D3Tek like this.
  6. robinton

    robinton Member

    Messages:
    44
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    33
    #6
    yeah i know
    it's just for learning and how to create this
     
    robinton, Jun 20, 2013 IP
  7. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665
    #7
    Then you need to state that up front - the OP didn't ask for out dated and insecure examples.
     
    sarahk, Jun 26, 2013 IP
    ryan_uk likes this.
  8. robinton

    robinton Member

    Messages:
    44
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    33
    #8
    sorry about this
    i didnt know it's out dated and insecure examples.
     
    robinton, Jun 26, 2013 IP
  9. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665
    #9
    so, did you know or didn't you?
     
    sarahk, Jun 26, 2013 IP
  10. robinton

    robinton Member

    Messages:
    44
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    33
    #10
    i didn't
     
    robinton, Jun 26, 2013 IP
  11. malky66

    malky66 Acclaimed Member

    Messages:
    3,996
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #11
    Well don't go giving advice on a subject you clearly know nothing about, leave it to the experts.
     
    malky66, Jun 26, 2013 IP