Change Bootstrap Navbar Color, Text and Hover Color

On 11/14/2017 6 Comments so far

Hi, we'll see how to change bootstrap navbar color, text and hover color. You can easily create website navigation menu with Bootstrap Navbar component. Though it comes in two different themes as lighter and darker shade, it may not serve everyone’s purpose. Changing bootstrap navbar color is simple than you think but while changing the background color you must also consider customizing text color and hover color, to make it more appealing.

If you know LESS or SASS then you can easily create custom bootstrap skin yourself. For those who didn't, don't worry. I'll show you how to override the navbar css elements of twitter bootstrap. Either you can create a new navbar class or override the default one in bootstrap framework.

Change Bootstrap Navbar Background, Text and Hover Color

First let's build a navbar component in bootstrap. Then I'll show you how to customize that bootstrap navbar.

Create Default Navbar in Bootstrap

<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <!-- logo -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mynavbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Koding Made Simple</a>
        </div>
        <!-- menu -->
        <div class="collapse navbar-collapse navbar-right" id="mynavbar">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Bootstrap</a></li>
                <li><a href="#">Themes</a></li>
                <li><a href="#">Blog</a></li>
            </ul>
        </div>
    </div>
</nav>

The above markup will generate a default navigation menu that looks like this in bootstrap. You can also add search box with icon to this navbar.

customize-bootstrap-default-navbar
Bootstrap Navbar - Before Changing Color

Now let us customize this.

Customize the Bootstrap Navbar Color

As I said earlier, we have to override bootstrap styles. It's better if you make all your changes in a separate stylesheet and attach it below the bootstrap css file. By this way bootstrap styles will be replaced with your own.

Here are the css modifications you have to make to change the navbar color.

.navbar-default {
    background-color: #CC0000;
    border-color: #AA0000;
    border-radius: 0;
}

.navbar-default .navbar-brand,
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
    color: #FFF;
}

.navbar-default .navbar-nav > li > a {
    color: #FFF;
}

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    background-color: #AA0000;
}

.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #FFF;
    background-color: #AA0000;
}

.navbar-default .navbar-text {
    color: #FFF;
}

.navbar-default .navbar-toggle {
    border-color: #AA0000;
}

.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
    background-color: #AA0000;
}

.navbar-default .navbar-toggle .icon-bar {
    background-color: #FFF;
}

All the above changes will make our bootstrap navbar to look like this.

change-bootstrap-navbar-color-text-hover-color
Bootstrap Navbar - After Changing Color

This is how it will look in the desktop view. As we know bootstrap is responsive, this navigation bar will collapse in mobile viewport like this.

bootstrap-navbar-mobile-collapsed-view
Bootstrap Navbar Mobile View - Collapsed

If you click on the striped button on the top-right corner, then the navbar will expand to show up the menu items like this.

bootstrap-navbar-mobile-expanded-view
Bootstrap Navbar Mobile View -Expanded

Note: Navbar collapse/expand option requires javascript. Make sure to include bootstrap.js file for this to work.

If you want to keep the default navbar untouched, then change the css class .navbar-default to something like .navbar-custom in the above code.

Here is how you can do it.

index.html

<!DOCTYPE html>
<html lang="en">
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Bootstrap Navbar Color</title>
    <link href="path/to/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="path/to/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<nav class="navbar navbar-custom" role="navigation">
    <div class="container-fluid">
        <!-- logo -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mynavbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Koding Made Simple</a>
        </div>
        <!-- menu -->
        <div class="collapse navbar-collapse navbar-right" id="mynavbar">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Bootstrap</a></li>
                <li><a href="#">Themes</a></li>
                <li><a href="#">Blog</a></li>
            </ul>
        </div>
    </div>
</nav>

<script src="path/to/jquery-1.10.2.js"></script>
<script src="path/to/bootstrap.js"></script>
</body>
</html>

style.css

.navbar-custom {
    background-color: #CC0000;
    border-color: #AA0000;
    border-radius: 0;
}

.navbar-custom .navbar-brand,
.navbar-custom .navbar-brand:hover,
.navbar-custom .navbar-brand:focus {
    color: #FFF;
}

.navbar-custom .navbar-nav > li > a {
    color: #FFF;
}

.navbar-custom .navbar-nav > li > a:hover,
.navbar-custom .navbar-nav > li > a:focus {
    background-color: #AA0000;
}

.navbar-custom .navbar-nav > .active > a,
.navbar-custom .navbar-nav > .active > a:hover,
.navbar-custom .navbar-nav > .active > a:focus {
    color: #FFF;
    background-color: #AA0000;
}

.navbar-custom .navbar-text {
    color: #FFF;
}

.navbar-custom .navbar-toggle {
    border-color: #AA0000;
}

.navbar-custom .navbar-toggle:hover,
.navbar-custom .navbar-toggle:focus {
    background-color: #AA0000;
}

.navbar-custom .navbar-toggle .icon-bar {
    background-color: #FFF;
}

Likewise you can change bootstrap navbar color, text and hover color easily. I hope you find this bootstrap navbar customization tutorial useful.

How to Create Simple Registration Form in CodeIgniter with Email Verification

On 11/14/2017 119 Comments so far

Hi, I have been writing codeigniter tutorials series for quite some time and already discussed about creating login form and contact form in codeigniter and bootstrap. One of the primitive features of any membership website is user registration system. Obviously the common trait of a signup form is to ask for too many details which will scare away users from your site. But keeping the form as minimal as possible will encourage them to sign up easily. Having said that today I’m going to show you, how to create a simple and elegant registration form in codeigniter along with email verification procedure.

Build Two-Step User Registration System with Email Verification

The codeigniter registration system we are going to build is a two step registration process namely 1. user registration and 2. user authentication process. It’s common now-a-days to send a confirmation link to user’s email-id during signup and activating the user’s account only when he/she confirms the email id they have provided at the time of registration. By this way we can keep away the spammers and attract only the serious users interested in the value provided by your site.

Must Read: Codeigniter Login, Logout & Sigup System using MySQL & Bootstrap

Steps for User Registration System

Here goes the flow for our user registration module.

  1. Ask user to fill in the basic details with email id in the registration form.
  2. Once validating the user submitted details, insert user data into database.
  3. Create a unique hash key and send a confirmation link to the user’s email id.
  4. User clicks on the confirmation link and return back to site.
  5. Verify the hash key within the link and activate the user’s account.

Download

Creating Registration Form in CodeIgniter with Email Verification

Now we’ll move on to implement the above registration procedure in codeigniter. Beforehand, we’ll create mysql database required to store the user’s details.

Create MySQL Database

First create a database named ‘mysite’ and run the below sql command to create the ‘user’ table to save data.

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `fname` varchar(30) NOT NULL,
  `lname` varchar(30) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(40) NOT NULL,
  `status` bit(1) NOT NULL DEFAULT b'0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

The status field is set by default to ‘0’ indicating the deactivate state of the user, and it will be set to ‘1’ for activating the user account once we confirm the email id.

Next we’ll move on to creating required codeigniter files for this registration module.

The Model (‘user_model.php’)

Create a model file named ‘user_model.php’ inside ‘application/models’ folder. Then copy paste the below code to the file.

<?php
class user_model extends CI_Model
{
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    //insert into user table
    function insertUser($data)
    {
        return $this->db->insert('user', $data);
    }
    
    //send verification email to user's email id
    function sendEmail($to_email)
    {
        $from_email = 'team@mydomain.com'; //change this to yours
        $subject = 'Verify Your Email Address';
        $message = 'Dear User,<br /><br />Please click on the below activation link to verify your email address.<br /><br /> http://www.mydomain.com/user/verify/' . md5($to_email) . '<br /><br /><br />Thanks<br />Mydomain Team';
        
        //configure email settings
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = 'ssl://smtp.mydomain.com'; //smtp host name
        $config['smtp_port'] = '465'; //smtp port number
        $config['smtp_user'] = $from_email;
        $config['smtp_pass'] = '********'; //$from_email password
        $config['mailtype'] = 'html';
        $config['charset'] = 'iso-8859-1';
        $config['wordwrap'] = TRUE;
        $config['newline'] = "\r\n"; //use double quotes
        $this->email->initialize($config);
        
        //send mail
        $this->email->from($from_email, 'Mydomain');
        $this->email->to($to_email);
        $this->email->subject($subject);
        $this->email->message($message);
        return $this->email->send();
    }
    
    //activate user account
    function verifyEmailID($key)
    {
        $data = array('status' => 1);
        $this->db->where('md5(email)', $key);
        return $this->db->update('user', $data);
    }
}
?>

This model file takes care of all the background communication and we have created three functions,

1. insertUser() to save the form data into database provided by user.

2. sendEmail() to send verification email to the user’s email id provided at the time of registration. Here we generate a unique hash key with the user’s email-id and attach it with a link and mail it to the user. Read this tutorial on sending email in codeigniter using smtp to learn more about configuring email settings.

3. verifyEmailID() to activate the user account after confirming the hash key from the earlier generated link. Here we update the status field from ‘0’ to ‘1’ representing the active state of the account.

Note: The above mentioned active state of the user will be used during user login process. Check this codeigniter login tutorial to see it in action.

The Controller (‘user.php’)

Next create a controller file named ‘user.php’ inside ‘application/controllers’ folder. And copy paste the below code to it.

<?php
class user extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('session', 'form_validation', 'email'));
        $this->load->database();
        $this->load->model('user_model');
    }
    
    function index()
    {
        $this->register();
    }

    function register()
    {
        //set validation rules
        $this->form_validation->set_rules('fname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
        $this->form_validation->set_rules('lname', 'Last Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
        $this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[user.email]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[cpassword]|md5');
        $this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required');
        
        //validate form input
        if ($this->form_validation->run() == FALSE)
        {
            // fails
            $this->load->view('user_registration_view');
        }
        else
        {
            //insert the user registration details into database
            $data = array(
                'fname' => $this->input->post('fname'),
                'lname' => $this->input->post('lname'),
                'email' => $this->input->post('email'),
                'password' => $this->input->post('password')
            );
            
            // insert form data into database
            if ($this->user_model->insertUser($data))
            {
                // send email
                if ($this->user_model->sendEmail($this->input->post('email')))
                {
                    // successfully sent mail
                    $this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-ID!!!</div>');
                    redirect('user/register');
                }
                else
                {
                    // error
                    $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                    redirect('user/register');
                }
            }
            else
            {
                // error
                $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                redirect('user/register');
            }
        }
    }
    
    function verify($hash=NULL)
    {
        if ($this->user_model->verifyEmailID($hash))
        {
            $this->session->set_flashdata('verify_msg','<div class="alert alert-success text-center">Your Email Address is successfully verified! Please login to access your account!</div>');
            redirect('user/register');
        }
        else
        {
            $this->session->set_flashdata('verify_msg','<div class="alert alert-danger text-center">Sorry! There is error verifying your Email Address!</div>');
            redirect('user/register');
        }
    }
}
?>

In the controller file we have created two functions namely, register() for the first step of the registration process and verify() for authenticating the user.

Also Read: How to Submit Form using AJAX in CodeIgniter

CodeIgniter Registration Form Validation

In the register() method, we asks the user to fill in the details, submit it and validate the form data. As I have said earlier, we have a signup form with minimal fields for first name, last name, email-id and password. It’s a good practice to ask the user to re-enter the password once again and we confirm if both the passwords match or not. If there is any mismatch we notify the user with an error message like this.

codeigniter-registration-form-validation-error

We also confirm if the email-id provided by user is unique and not used already for another account. Codeigniter provides a simple way to confirm this with the built-in validation function is_unique[user.email] where ‘user’ is the database table name and ‘email’ is the database column name to check out.

Once we validate the user details and confirm everything is ok, we insert the data into database with the line $this->user_model->insertUser($data). And send the mail to user’s email-id using $this->user_model->sendEmail($this->input->post('email')).

For generating the hash key, I have md5() ‘ed the user’s email-id and sent it with the confirmation link. By this way, we don’t have to store a separate hash key in the database for each user. However you can generate a random hash and store in the database for later verification. It’s up to you.

After successfully sending the email, we notify the user to confirm their email-id to complete the registration process like this.

codeigniter-signup-form

Later when the user clicks on the email link, they will be taken back to the site and to the verify() function in the controller. The hash code will be tested against the email id stored in the database and that particular user account will be activated and will be promptly notified like this.

codeigniter-email-verification-success-message

Related Read: Beginners Guide to Database CRUD using CodeIgniter and Bootstrap

The View (‘user_registration_view.php’)

We have created model and controller file for user registration. Now it’s time to build user interface i.e., registration form with all the required form fields. For that create a view file named ‘user_registration_view.php’ inside ‘application/views’ folder and copy paste the below code to it.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter User Registration Form Demo</title>
    <link href="<?php echo base_url("bootstrap/css/bootstrap.css"); ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <?php echo $this->session->flashdata('verify_msg'); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4>User Registration Form</h4>
            </div>
            <div class="panel-body">
                <?php $attributes = array("name" => "registrationform");
                echo form_open("user/register", $attributes);?>
                <div class="form-group">
                    <label for="name">First Name</label>
                    <input class="form-control" name="fname" placeholder="Your First Name" type="text" value="<?php echo set_value('fname'); ?>" />
                    <span class="text-danger"><?php echo form_error('fname'); ?></span>
                </div>

                <div class="form-group">
                    <label for="name">Last Name</label>
                    <input class="form-control" name="lname" placeholder="Last Name" type="text" value="<?php echo set_value('lname'); ?>" />
                    <span class="text-danger"><?php echo form_error('lname'); ?></span>
                </div>
                
                <div class="form-group">
                    <label for="email">Email ID</label>
                    <input class="form-control" name="email" placeholder="Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
                    <span class="text-danger"><?php echo form_error('email'); ?></span>
                </div>

                <div class="form-group">
                    <label for="subject">Password</label>
                    <input class="form-control" name="password" placeholder="Password" type="password" />
                    <span class="text-danger"><?php echo form_error('password'); ?></span>
                </div>

                <div class="form-group">
                    <label for="subject">Confirm Password</label>
                    <input class="form-control" name="cpassword" placeholder="Confirm Password" type="password" />
                    <span class="text-danger"><?php echo form_error('cpassword'); ?></span>
                </div>

                <div class="form-group">
                    <button name="submit" type="submit" class="btn btn-default">Signup</button>
                    <button name="cancel" type="reset" class="btn btn-default">Cancel</button>
                </div>
                <?php echo form_close(); ?>
                <?php echo $this->session->flashdata('msg'); ?>
            </div>
        </div>
    </div>
</div>
</div>
</body>
</html>

Note: As for the style sheet I used twitter bootstrap css, but feel free to use your own if you prefer.

Recommended Read: Quick Guide to Integrate Twitter Bootstrap CSS with CodeIgniter

The above view file produces a minimal and elegant registration form like this.

codeigniter-bootstrap-registration-form-example

As you can see in the view file, I have used several css styles (‘class’) to quickly design this form and those are Bootstrap’s build-in form classes. To display the form validation errors, I have used codeigniter’s form_error() function below the corresponding form input fields.

Also the line $this->session->flashdata(); is used to notify success/failure message after registration process. Unlike simple echoed messages, the flashdata message will be displayed only once after the redirection takes place.

And that was all about creating user registration form in codeigniter with email confirmation. I hope this two step registration system will be helpful to you. If you have any trouble implementing it, please voice it through your comments.

Recommended Read:

P.S.: For those who faced password matching issues, I have tweaked the validation rules a little to fix it. You can check it now.

Last Modified: 14-Nov-2017


Scrollable Table with Fixed Header in Bootstrap Example

On 11/14/2017 2 Comments so far

Hi! This post shows you how to create scrollable table with fixed header in bootstrap. As a Back-end Developer I have to deal with databases a lot and often to display data in html table in the front-end. And with readily available bootstrap css, you can easily style tables in seconds. Bootstrap comes with several table styles like striped, bordered, condensed and even responsive which adds horizontal scrollbar to tables thus making the data easily viewable on mobile devices.

When you have large dataset to show on table, then it's better to split data over multiple pages using pagination. But recently I have to go for another option which is to make bootstrap table vertically scrollable with fixed header.

I looked around the net for some good solution but nothing is satisfactory. I tweaked the css a little and achieved a satisfactory result. Here I'll show you how I made bootstrap table scrollable with fixed header.

Creating Bootstrap Scrollable Table with Fixed Header:

Step-1) Add HTML Markup for Bootstrap Table

First add some markup for a bootstrap table. Here I created a striped table but also have added a custom table class .table-scroll which adds vertical scroll bar to the table and makes the table header fixed while scrolling down.

<div class="col-xs-8 col-xs-offset-2 well">
    <table class="table table-scroll table-striped">
        <thead>
            <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>County</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Andrew</td>
                <td>Jackson</td>
                <td>Washington</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Thomas</td>
                <td>Marion</td>
                <td>Jackson</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Benjamin</td>
                <td>Warren</td>
                <td>Lincoln</td>
            </tr>
            <tr>
                <td>4</td>
                <td>Grant</td>
                <td>Wayne</td>
                <td>Union</td>
            </tr>
            <tr>
                <td>5</td>
                <td>John</td>
                <td>Adams</td>
                <td>Marshall</td>
            </tr>
            <tr>
                <td>6</td>
                <td>Morgan</td>
                <td>Lee</td>
                <td>Lake</td>
            </tr>
            <tr>
                <td>7</td>
                <td>John</td>
                <td>Henry</td>
                <td>Brown</td>
            </tr>
            <tr>
                <td>8</td>
                <td>William</td>
                <td>Jacob</td>
                <td>Orange</td>
            </tr>
            <tr>
                <td>9</td>
                <td>Kelly</td>
                <td>Davidson</td>
                <td>Taylor</td>
            </tr>
            <tr>
                <td>10</td>
                <td>Colleen</td>
                <td>Hurst</td>
                <td>Randolph</td>
            </tr>
            <tr>
                <td>11</td>
                <td>Rhona</td>
                <td>Herrod</td>
                <td>Cumberland</td>
            </tr>
            <tr>
                <td>12</td>
                <td>Jane</td>
                <td>Paul</td>
                <td>Marshall</td>
            </tr>
            <tr>
                <td>13</td>
                <td>Ashton</td>
                <td>Fox</td>
                <td>Calhoun</td>
            </tr>
            <tr>
                <td>14</td>
                <td>Garrett</td>
                <td>John</td>
                <td>Madison</td>
            </tr>
            <tr>
                <td>15</td>
                <td>Fredie</td>
                <td>Winters</td>
                <td>Washington</td>
            </tr>
        </tbody>
    </table>
</div>

Step-2) Add Custom CSS

Next we have to add custom css to bootstrap. Here are the css styles for the class .table-scroll we have already created. Copy these styles to a separate style sheet and link them next to bootstrap.css file.

<style type="text/css">
.well {
    background: none;
    height: 320px;
}

.table-scroll tbody {
    position: absolute;
    overflow-y: scroll;
    height: 250px;
}

.table-scroll tr {
    width: 100%;
    table-layout: fixed;
    display: inline-table;
}

.table-scroll thead > tr > th {
    border: none;
}
</style>

The above fix will produce the desired result. You can see a nice scrollable table with fixed header in bootstrap.

bootstrap-table-scroll-fixed-header-example

Read Also: Center Table on Div / Page in Bootstrap Example

Don't Miss: Modal Image Popup On Click / Hover in Bootstrap

Likewise you can easily create scrollable table with fixed header in bootstrap css.

How to Send Email in CodeIgniter via SMTP Server

On 11/14/2017 9 Comments so far

Codeigniter comes with many built-in helpers and libraries for robust development. Of which its email library is a little gem that you can configure and send mails on fly. Here is a simple example to send email in codeigniter using smtp protocol. We'll see how to send mail with attachments through gmail, but you can use any third party smtp servers. Just get the smtp settings from the service provider and use it instead of gmail settings and you are done.

To send mail in codeigniter, you have to configure your email preferences like mail protocol, smtp authorization, html or plain text mail etc. These email preferences can be defined either globally or at the time of sending mails (like inside controllers).

Also Read:

Configure Email Settings

Here we'll configure our email settings globally in codeigniter. Create a file named 'email.php' inside 'application/config' folder and add the below settings to it. These settings will be loaded and used automatically for sending emails.

<?php
    $config['protocol'] = 'smtp';
    $config['smtp_host'] = 'ssl://smtp.gmail.com'; //change this
    $config['smtp_port'] = '465';
    $config['smtp_user'] = 'user@gmail.com'; //change this
    $config['smtp_pass'] = 'password'; //change this
    $config['mailtype'] = 'html';
    $config['charset'] = 'iso-8859-1';
    $config['wordwrap'] = TRUE;
    $config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
?>

The above is the smtp settings for gmail. The 'smtp_user' is your (gmail) email id and 'smtp_pass' is the email password.

Next we have to load the codeigniter email library and use its methods to send mail.

Sending Email in Codeigniter using Gmail

Use this sendmail() function in a controller file to send email. You can load the 'email' library either inside the function or in the controller constructor.

<?php
//send mail
function sendmail()
{
    $this->load->library('email'); // load email library
    $this->email->from('user@gmail.com', 'sender name');
    $this->email->to('test1@gmail.com');
    $this->email->cc('test2@gmail.com'); 
    $this->email->subject('Your Subject');
    $this->email->message('Your Message');
    $this->email->attach('/path/to/file1.png'); // attach file
    $this->email->attach('/path/to/file2.pdf');
    if ($this->email->send())
        echo "Mail Sent!";
    else
        echo "There is error in sending mail!";
}
?>

All the above email methods like from(), to() are pretty self explanatory and I'll leave it to you. The method $this->email->send() will return a boolean value based upon if email is sent or not.

If you want to send mail in bulk, use comma separated email-id's in $this->email->to() method like this.

$this->email->to('test1@gmail.com, test2@gmail.com, test3@gmail.com');

Also Read:

That's all about sending email in codeigniter via smtp. I hope you like this tutorial. Please don't forget to share in social networks.

Last Modified: 14-Nov-2017

How to integrate Twitter Bootstrap with PHP CodeIgniter Framework

On 11/14/2017 33 Comments so far

Hi, as a nice addition to our codeigniter tutorials series, I'm back with another article which discusses about CodeIgniter and Bootstrap integration. This will teach you the technique of combining the power of two robust frameworks, PHP CodeIgniter and Twitter Bootstrap. You should properly integrate twitter bootstrap 3 with code igniter framework for it to work. I'm going to assume you are individually acquainted with CodeIgniter and Bootstrap frameworks, so in this tutorial will just show you how to integrate Bootstrap with CodeIgniter by which you can enhance the appearance of your CodeIgniter application.

In case you don't have, download the latest versions of the frameworks from the links given below.

Step-by-Step Instruction for CodeIgniter Bootstrap Integration

STEP-1) First download and extract the PHP CodeIgniter framework zip file to your working folder. Then create a folder named "assets" to keep all your bootstrap files. Just make sure your CodeIgniter folder structure is similar to the below image.

integrate-twitter-bootstrap-with-codeIgniter

Recommended Read: How to Create Login Form in CodeIgniter, MySQL and Twitter Bootstrap

Recommended Read: How to Create User Registration Form in CodeIgniter, MySQL & Bootstrap

STEP-2) Next extract and move the css, js and fonts folder of Twitter bootstrap CSS to the "assets" folder we have created in STEP-1.

use-twitter-bootstrap-with-codeIgniter

STEP-3) We need jQuery library for the Bootstrap's js plugins to work. So move the jQuery file to the "assests/js" folder.

Now the setup is over. To start using bootstrap in CodeIgniter, we have to include the bootstrap ".css" and ".js" files to CodeIgniter views.

To include the bootstrap css file, add this line above the </head> tag in the CodeIgniter view file.

<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" />

Next we have to include js files for which you should add the below code just before the </body> tag.

<script type="text/javascript" src="<?php echo base_url("assets/js/jQuery-1.10.2.js"); ?>"></script>
<script type="text/javascript" src="<?php echo base_url("assets/js/bootstrap.js"); ?>"></script>

Note: Make sure you always add the jQuery library before "bootstrap.js".

Recommended Read: CodeIgniter Bootstrap Tutorial - Read and Display data from MySQL Database

Recommended Read: CodeIgniter Bootstrap: Insert Form Data into Database with Field Validations

Having setup the environment to use Twitter Bootstrap with CodeIgniter, our app is ready for development.

How to Use Bootstrap CSS in CodeIgniter?

Now we have bootstrap files in place. The next question that rise would be where and how to use this bootstrap css in codeigniter?

Well! As I have already said bootstrap is just a ready-made stylesheet but with higher flexibility. You have to include it's css styles in html tags as you would normally do. Just take this example. I have added a simple comment form in codeigniter view.

<div>
    <?php $attributes = array("name" => "comment-form");
    echo form_open("user_comments/submit", $attributes);?>
        <div class="form-group">
            <textarea name="comment" placeholder="Your comments..." rows="4"></textarea>
        </div>
        <div class="form-group">
            <input type="submit" name="submit" value="Post Comment">
        </div>
    <?php echo form_close(); ?>
</div>

As there are no css styles added to beautify the form, it looks plain simple like this,

use-bootstap-in-codeigniter-before

Next I have included some css classes from bootstrap to this very same form.

    
<div class="well" style="width:50%; margin: 0 auto;">
    <?php $attributes = array("name" => "comment-form");
    echo form_open("user_comments/submit", $attributes);?>
        <div class="form-group">
            <textarea name="comment" placeholder="Your comments..." rows="4" class="form-control"></textarea>
        </div>
        <div class="form-group">
            <input type="submit" name="submit" value="Post Comment" class="btn btn-danger">
        </div>
    <?php echo form_close(); ?>
</div>

Boom! The form looks much more pleasing now without writing any of those styles of our own.

use-bootstap-in-codeigniter-after

Convenient! I think you have got a good idea about bootstrap now. You can customize bootstrap css to your liking without trouble. And to be honest it will take a while for you to get around with bootstrap elements.

For more detailed usage head over to our codeigniter section and start reading. I have used bootstrap css in almost all of my codeigniter tutorials.

Loading Bootstrap CSS via CDN:

Here's the good news. Bootstrap is available in CDN and you don't even have to download it to your own server for using it. Just directly load it from maxcdn like this,

<!DOCTYPE html>
<html>
    <head>
        <meta content="width=device-width, initial-scale=1.0" name="viewport" >
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
    </head>
    <body>
    
        ...
        ...
    
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
    </body>
</html>

If you use slow server then take advantage of this CDN route for using bootstrap.

I hope you have enjoyed this CodeIgniter Bootstrap Tutorial.

Last-Modified: 14-Nov-2017

Insert Array into MySQL Database using PHP

On 11/13/2017 Be the first to comment!

Hi! Today let's see how to insert array into mysql database using php. A frequently asked question by budding developers but not without reason. Since databases don't support array data types, there is no direct way to store them in db. But you can convert array as string and insert into mysql. There are two ways you can do it, one is by serializing the array and the other is saving it as json string.

But before going into the process, I must warn you it's a bad idea to store array in database as it is against the normalization theory of relational database and you cannot easily query the data later. Nevertheless, sometimes I used to store array in database for temporary log and you can also do it.

insert php array into mysql database

How to Insert Array into MySQL with PHP?

The first method we are going to see is about serializing php array to string. In PHP, we have two methods, serialize() and unserialize(), the first one converts array to string and the latter reverts back the string to array.

To Convert Array to String:
<?php
$array = array("name"=>"johnson", "code"=>"12345", "status"=>"true");
$string = serialize($array);
echo $string;

// output
// a:3:{s:4:"name";s:7:"johnson";s:4:"code";s:5:"12345";s:6:"status";s:4:"true";}
?>
To Convert Serialized String to Array:
<?php
$array = unserialize($string);
echo "<pre>";
print_r($array);

// output
// Array
// (
//     [name] => johnson
//     [code] => 12345
//     [status] => true
// )
?>

Method 1) Serialize Array and Save into MySQL

Now let's see about storing array in mysql with the above method. First we should convert the given array to string with serialize() function and then insert into database. Here's the php code to do it.

<?php
$con = mysqli_connect("localhost", "username", "password", "db_demo");
$user_data = array("name"=>"johnson", "code"=>"12345", "status"=>"true");
$serialized_data = serialize($user_data);

$sql = "insert into user_logs (details, created) value ('{$serialized_data}', NOW())";
mysqli_query($con, $sql);
?>

Retrieve Array Data from MySQL:

<?php
$con = mysqli_connect("localhost", "username", "password", "db_demo");
$sql = "select details from user_logs";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result))
{
   $array = unserialize($row["details"]);
   print_r($array);
}
?>

After fetching the serialized string from database, you have to use unserialize() function to turn them back into the original array. Simple as that!

Method 2) Store Array as JSON String in MySQL

The second method is to convert the array into a json string and insert into mysql. I mostly prefer this than the previous one, as json is more portable and compatible with javascript and other languages.

Basically, you have to encode the array as JSON string with json_encode() function and store it in database. Here's how to do it.

<?php
$con = mysqli_connect("localhost", "username", "password", "db_demo");
$data = array("name"=>"johnson", "code"=>"12345", "status"=>"true");
$json = json_encode($data);
$sql = "insert into user_logs (details, created) value ('{$json}', NOW())";
mysqli_query($con, $sql);
?>

Fetch JSON from DB:

<?php
$con = mysqli_connect("localhost", "username", "password", "db_demo");
$result = mysqli_query($con, "select details from user_logs");
while($row = mysqli_fetch_array($result))
{
   $arr = json_decode($row["details"], true);
   var_dump($arr);
}
?>

Here we fetch the json string which we have stored previously in the database and decode it into an array using json_decode() function.

Read:

That explains about inserting array into mysql database in php. Between the two methods, going with json is much more preferred and can be easily read by other languages. Also MySQL5.7.8 and above has native JSON support, so you can save json string directly in the table column. I hope you like this tutorial. If you find this useful, please share it with your friends.

How to Fetch Data from Database in CodeIgniter

On 11/13/2017 11 Comments so far

How to fetch data from database in codeigniter? CodeIgniter is the simplest and light PHP framework which lets you create robust web applications in no time. Using Twitter Bootstrap with CodeIgniter saves the hassle of writing CSS Stylesheets for your app and lets you focus on development. Later you can customize bootstrap styles to suit your need. That is the best part of using MVC pattern as the presentation (view) is separate, you can change the look and feel of the app anytime without disturbing the rest of it.

kodingmadesimple.com have good amount of twitter bootstrap tutorials about customizing bootstrap 3 and I recommend you to go through our bootstrap tutorials section.

Fetch Data from Database in CodeIgniter:

Now we'll see how to read data from MySQL Database and display it in a neat table format with Bootstrap. Since we are going to use bootstrap we don't want to write any custom stylesheets for formatting the display. If you are not familiar with using Bootstrap with CodeIgniter, then you must read this tutorial on How to integrate Bootstrap with CodeIgniter.

In this CodeIgniter tutorial, I'm going to read data from the MySQL database and display it in a neat table format using Bootstrap3. For example assume we have a DB called employee which has the below two tables.

tbl_dept (int_id | var_dept_name | int_hod)
tbl_emp (int_id | var_emp_name | int_dept_id)

Now I want to display the entire department list along with the head-of-department employee name.

1. First create the model with name department_model.php in the folder system/application/models. Then add a function to read the department list from the DB.

department_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class department_model extends CI_Model{
     function __construct()
     {
          // Call the Model constructor
          parent::__construct();
     }

     //read the department list from db
     function get_department_list()
     {
          $sql = 'select var_dept_name, var_emp_name from tbl_dept, tbl_emp where tbl_dept.int_hod = tbl_emp.int_id';
          $query = $this->db->query($sql);
          $result = $query->result();
          return $result;
     }
}

2. Next create the controller file with name department.php in the folder system/application/controllers. In this controller call the model function to get the department list and pass it to the view file for presentation.

department.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 class department extends CI_Controller {
     public function __construct()
     {
          parent::__construct();
          $this->load->helper('url');
          $this->load->database();
     }

     public function index()
     {
          //load the department_model
          $this->load->model('department_model');  
          //call the model function to get the department data
          $deptresult = $this->department_model->get_department_list();           
          $data['deptlist'] = $deptresult;
          //load the department_view
          $this->load->view('department_view',$data);
     }
}

3. Finally create the view file with name department_view.php in the folder system/application/views. Now parse the data received from the controller one by one and display it. In order to display the department lists in a neat table format use the bootstrap built-in classes table, table-striped & table-hover.

department_view.php
<html>
     <head>
          <title>Department Master</title>
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <!--link the bootstrap css file-->
          <link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>">
     </head>
     <body>
          <div class="container">
          <div class="row">
          <div class="col-lg-12 col-sm-12">
               <table class="table table-striped table-hover">
                    <thead>
                         <tr>
                              <th>#</th>
                              <th>Department Name</th>
                              <th>Head of Department</th>
                         </tr>
                    </thead>
                    <tbody>
                         <?php for ($i = 0; $i < count($deptlist); ++$i) { ?>
                              <tr>
                                   <td><?php echo ($i+1); ?></td>
                                   <td><?php echo $deptlist[$i]->var_dept_name; ?></td>
                                   <td><?php echo $deptlist[$i]->var_emp_name; ?></td>
                              </tr>
                         <?php } ?>
                    </tbody>
               </table>
          </div>
          </div>
          </div>
     </body>
</html>

Related: CodeIgniter Pagination using Twitter Bootstrap CSS

Here is the table view of the above example

codeigniter-fetch-data-from-database

As I've said earlier in this tutorial we haven't written any CSS styles of our own, yet we get a neatly formatted table list by using bootstrap classes (Nice isn't it?).

Read:

That explains about fetching data from database in codeigniter and display it in html table using bootstrap.

Last Modified: 13-Nov-2017

Contact Form

Name

Email *

Message *