Multi-step Registration form using Codeigniter, MySQL, jQuery

You may also like to read:

Introduction

Here we will see example on multi-step registration form using Codeigniter, MySQL, jQuery. Here we will insert data into database using multi-step registration step. Sometimes we need to capture lots of user details during registration process and as a result we got long forms on web page. So the best solution is to break the form into smaller logical section and present it into a multi-step registration form. This type of mult-step registration form always improves usability on web page comparing to very long form.

I am going to explain how to convert very long form into multi-step registration form using Codeigniter, MySQL and jQuery.

Prerequisite

Apache 2.4, PHP 7.0.15, Codeigniter 3.1.10

Example with Source Code

Go through below steps.

Creating Project Directory

Create a project directory called codeIgniter-3.1.10-multi-step-registration under your <Apache 2.4 installation directory>/htdocs. Now extract your Codeigniter framework zip folder inside the project directory.

Creating MySQL Table

Create a table called users in MySQL database. Create database roytuts in MySQL server if it does not exist already.

CREATE TABLE `users` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`password` VARCHAR(255) NULL,
	`email` VARCHAR(100) NULL,
	`phone` INT(10) NOT NULL,
	`gender` VARCHAR(6) NOT NULL,
	`dob` VARCHAR(10) NOT NULL,
	`address` VARCHAR(255) NOT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

Configuring Autoload

Open application/config/autoload.php file and auto-load few things to use uniformly throughout the application without loading again while using.

$autoload['libraries'] = array('database', 'form_validation');
$autoload['helper'] = array('html', 'url', 'file', 'form');

Configuring Database

Open application/config/database.php file and make required changes for database configurations.

'username' => 'root',
'password' => '',
'database' => 'roytuts'

If you have password for the database then put appropriate password.

Creating Model Class

Create Model class for database operations. In our case we will insert data into MySQL table using multi-step registration form.

<?php

/**
 * Description of UserModel
 *
 * @author https://www.roytuts.com
 */
class UserModel extends CI_Model {

    private $user_table = 'users';

    function __construct() {
        parent::__construct();
    }

    function insert_user($name, $password, $email, $phone, $gender, $dob, $address) {
        $data = array('name' => $name, 'password' => md5($password), 'email' => $email, 'phone' => $phone, 'gender' => $gender, 'dob' => $dob, 'address' => $address);
        $result = $this->db->insert($this->user_table, $data);
        if ($result !== NULL) {
            return TRUE;
        }
        return FALSE;
    }

}

Creating Controller Class

Create Controller class to handle request/response for end users.

<?php

/**
 * Description of UserController
 *
 * @author https://www.roytuts.com
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class UserController extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('usermodel');
    }

    public function index() {
        if ($this->input->post('finish')) {
            $this->form_validation->set_rules('name', 'Full Name', 'trim|required');
            $this->form_validation->set_rules('password', 'Password', 'trim|required');
            $this->form_validation->set_rules('email', 'Email Address', 'trim|required');
            $this->form_validation->set_rules('phone', 'Phone No.', 'trim|required');
            $this->form_validation->set_rules('gender', 'Gender', 'trim|required');
            $this->form_validation->set_rules('dob', 'Date of Birth', 'trim|required');
            $this->form_validation->set_rules('address', 'Contact Address', 'trim|required');

            if ($this->form_validation->run() !== FALSE) {
                $result = $this->usermodel->insert_user($this->input->post('name'), $this->input->post('password'), $this->input->post('email'), $this->input->post('phone'), $this->input->post('gender'), $this->input->post('dob'), $this->input->post('address'));
                $data['success'] = $result;
                $this->load->view('user', $data);
            } else {
                $this->load->view('user');
            }
        } else {
            $this->load->view('user');
        }
    }

}

Creating View File

Create View file for creating multi-step registration form. We will use jQuery to validate the user input before we save into the MySQL table. We will also validate whether user has input all the required input fields before going to the next step.

<html>
    <head>
        <title>Multi Step Registration</title>
        <style>
            body {
                font-family:tahoma;
                font-size:12px;
            }

            #signup-step {
                margin:auto;
                padding:0;
                width:53%
            }

            #signup-step li {
                list-style:none; 
                float:left;
                padding:5px 10px;
                border-top:#004C9C 1px solid;
                border-left:#004C9C 1px solid;
                border-right:#004C9C 1px solid;
                border-radius:5px 5px 0 0;
            }

            .active {
                color:#FFF;
            }

            #signup-step li.active {
                background-color:#004C9C;
            }

            #signup-form {
                clear:both;
                border:1px #004C9C solid;
                padding:20px;
                width:50%;
                margin:auto;
            }

            .demoInputBox {
                padding: 10px;
                border: #CDCDCD 1px solid;
                border-radius: 4px;
                background-color: #FFF;
                width: 50%;
            }

            .signup-error {
                color:#FF0000; 
                padding-left:15px;
            }

            .message {
                color: #00FF00;
                font-weight: bold;
                width: 100%;
                padding: 10;
            }

            .btnAction {
                padding: 5px 10px;
                background-color: #F00;
                border: 0;
                color: #FFF;
                cursor: pointer;
                margin-top:15px;
            }

            label {
                line-height:35px;
            }

        </style>

        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>

        <script>
            function validate() {
                var output = true;
                $(".signup-error").html('');

                if ($("#personal-field").css('display') != 'none') {
                    if (!($("#name").val())) {
                        output = false;
                        $("#name-error").html("Name required!");
                    }

                    if (!($("#dob").val())) {
                        output = false;
                        $("#dob-error").html("Date of Birth required!");
                    }
                }

                if ($("#password-field").css('display') != 'none') {
                    if (!($("#user-password").val())) {
                        output = false;
                        $("#password-error").html("Password required!");
                    }

                    if (!($("#confirm-password").val())) {
                        output = false;
                        $("#confirm-password-error").html("Confirm password required!");
                    }

                    if ($("#user-password").val() != $("#confirm-password").val()) {
                        output = false;
                        $("#confirm-password-error").html("Password not matched!");
                    }
                }

                if ($("#contact-field").css('display') != 'none') {
                    if (!($("#phone").val())) {
                        output = false;
                        $("#phone-error").html("Phone required!");
                    }

                    if (!($("#email").val())) {
                        output = false;
                        $("#email-error").html("Email required!");
                    }

                    if (!$("#email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
                        $("#email-error").html("Invalid Email!");
                        output = false;
                    }

                    if (!($("#address").val())) {
                        output = false;
                        $("#address-error").html("Address required!");
                    }
                }

                return output;
            }

            $(document).ready(function () {
                $("#next").click(function () {
                    var output = validate();
                    if (output === true) {
                        var current = $(".active");
                        var next = $(".active").next("li");
                        if (next.length > 0) {
                            $("#" + current.attr("id") + "-field").hide();
                            $("#" + next.attr("id") + "-field").show();
                            $("#back").show();
                            $("#finish").hide();
                            $(".active").removeClass("active");
                            next.addClass("active");
                            if ($(".active").attr("id") == $("li").last().attr("id")) {
                                $("#next").hide();
                                $("#finish").show();
                            }
                        }
                    }
                });


                $("#back").click(function () {
                    var current = $(".active");
                    var prev = $(".active").prev("li");
                    if (prev.length > 0) {
                        $("#" + current.attr("id") + "-field").hide();
                        $("#" + prev.attr("id") + "-field").show();
                        $("#next").show();
                        $("#finish").hide();
                        $(".active").removeClass("active");
                        prev.addClass("active");
                        if ($(".active").attr("id") == $("li").first().attr("id")) {
                            $("#back").hide();
                        }
                    }
                });

                $("input#finish").click(function (e) {
                    var output = validate();
                    var current = $(".active");

                    if (output === true) {
                        return true;
                    } else {
                        //prevent refresh
                        e.preventDefault();
                        $("#" + current.attr("id") + "-field").show();
                        $("#back").show();
                        $("#finish").show();
                    }
                });
            });
        </script>

    </head>
    <body>

        <ul id="signup-step">
            <li id="personal" class="active">Personal Detail</li>
            <li id="password">Password</li>
            <li id="contact">Contact</li>
        </ul>

        <?php
        if (isset($success)) {
            echo '<div>User record inserted successfully</div>';
        }

        $attributes = array('name' => 'frmRegistration', 'id' => 'signup-form');
        echo form_open($this->uri->uri_string(), $attributes);
        ?>
        <div id="personal-field">
            <label>Name</label><span id="name-error" class="signup-error"></span>
            <div><input type="text" name="name" id="name" class="demoInputBox"/></div>
            <label>Date of Birth</label><span id="dob-error" class="signup-error"></span>
            <div><input type="text" name="dob" id="dob" class="demoInputBox"/></div>
            <label>Gender</label>
            <div>
                <select name="gender" id="gender" class="demoInputBox">
                    <option value="male">Male</option>
                    <option value="female">Female</option>                                                                         
                </select>
            </div>
        </div>

        <div id="password-field" style="display:none;">
            <label>Enter Password</label><span id="password-error" class="signup-error"></span>
            <div><input type="password" name="password" id="user-password" class="demoInputBox" /></div>
            <label>Re-enter Password</label><span id="confirm-password-error" class="signup-error"></span>
            <div><input type="password" name="confirm-password" id="confirm-password" class="demoInputBox" /></div>
        </div>

        <div id="contact-field" style="display:none;">
            <label>Phone</label><span id="phone-error" class="signup-error"></span>
            <div><input type="text" name="phone" id="phone" class="demoInputBox" /></div>
            <label>Email</label><span id="email-error" class="signup-error"></span>
            <div><input type="text" name="email" id="email" class="demoInputBox" /></div>
            <label>Address</label><span id="address-error" class="signup-error"></span>
            <div><textarea name="address" id="address" class="demoInputBox" rows="5" cols="50"></textarea></div>
        </div>

        <div>
            <input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
            <input class="btnAction" type="button" name="next" id="next" value="Next" >
            <input class="btnAction" type="submit" name="finish" id="finish" value="Finish" style="display:none;">
        </div>
        <?php echo form_close(); ?>

    </body>
</html>

Configuring Route

Open file application/config/routes.php and change the default controller.

$route['default_controller'] = 'usercontroller';

Testing the Application

Now run the application and hit the URL http://[::1]/codeIgniter-3.1.10-multi-step-registration/index.php in the browser. You will see below output on the browser.

multi step form using codeigniter mysql jquery

If you try to submit the form without filling data then you will see validation errors.

You will also see that you cannot proceed to the next step until you fill all required fields in the current step.

Once you fill the form with all input fields and you will find one row has been inserted into the database table and you will see the below response above the form

User record inserted successfully

Source Code

You can download source code.

Thanks for reading.

Multi-step Registration form using Codeigniter, MySQL, jQuery

2 thoughts on “Multi-step Registration form using Codeigniter, MySQL, jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top