Multi-Step Registration Form Using Codeigniter, MySQL, jQuery

Table of Contents

Introduction

Here you will see example on multi-step registration form using Codeigniter 3, MySQL, jQuery. Here I will insert data into database using multi-step registration step. Sometimes you may need to capture lots of user details during registration process and as a result you get a long form 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 multistep 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.

You may also like to read Python, Flask Multi-step registration form with MySQL, jQuery

Prerequisites

Apache 2.4 (Optional), PHP 7.0.15 – 7.4.27, Codeigniter 3.1.10 – 3.1.1, MySQL 5.x – 8.x, jQuery 1.10.2 – 3.6.0

Project Directory

Create a project directory called codeIgniter-multi-step-registration under your <Apache 2.4 installation directory>/htdocs or anywhere (if you are not using external server to run your app) in the physical drive in your system. Now extract your Codeigniter framework zip folder inside the project directory.

MySQL Table

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

You may use the following table structure for MySQL version below 8.

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;

For MySQL version 8, you can use the following table structure:

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

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', 'form');

Configuring Database

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

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

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

For MySQL version 8, you can also change the charset as shown below:

...
'char_set' => 'utf8mb4',
'dbcollat' => 'utf8mb4_unicode_ci',
...

Model Class

Create Model class for database operations. Here, I will insert data into MySQL table using multi-step registration form. The model class file name is application/model/UserModel.php.

<?php

/**
 * Description of UserModel
 *
 * @author https://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;
    }

}

Controller Class

Create Controller class to handle request/response for end users. The controller code is written into the file application/controllers/UserController.php.

<?php

/**
 * Description of UserController
 *
 * @author https://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');
        }
    }

}

View File

Create View file for creating multi-step registration form. I will use jQuery to validate the user input before I save into the MySQL table. I will also validate whether user has input all the required input fields before going to the next step. The view file name is application/views/user.php.

<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 src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></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 Multi Step Form

Now run the application and hit the URL http://localhost/ in the browser. You will see the following 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

Download

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 *