Codeigniter – Insert

Codeigniter – Insert

This tutorial will show you how to add record to database using Codeigniter.

I will use Codeigniter’s Active Record for database queries which is a safer way to execute queries than raw SQL.

Before we begin with Codeigniter Create Tutorial, you need to set up your Codeigniter.

Setting up CodeIgniter Framework

Also, you need to configure your CodeIgniter for this tutorial.

CodeIgniter Configuration


Lets start with our first lesson and that is inserting data to database.

Controllers are used for communication between clients and server.

Communication looks like this:

Client send request via web browser to controller.

Controller than passes user’s request to model or view, depends what’s the purpose of that controller.

After that, controller sends result to client.

That’s called MVC pattern, and it’s a very common in programming languages.

After some details about CodeIgniter principles, we can continue with our tutorial.

 

Autoload

I will add models, helpers and other stuff to autoload.php because it’s a little easier in case you forget to include some of that in controller’s functions, this way you can avoid possible errors.

Open autoload.php in application/config directory and find these lines

$autoload['libraries'] = array();
$autoload['helper'] = array();
$autoload['model'] = array();

And make sure they look like this

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

Now that we have loaded everything we need, we can proceed with creating controller.

 

Controller

Create new php file in application/controllers folder, we can name it Site, this will be our main controller for now.

I will use CodeIgniter’s built in Form Validation which you can use to ensure that user inputs only value that is allowed to avoid possible errors.

Site.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Site extends CI_Controller {

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

    public function index()
    {
        $this->load->view('site');
    }

    public function add()
    {
        $this->form_validation->set_rules('name', 'Component Name', 'required|is_unique[components.ComponentName]|max_length[64]');
        $this->form_validation->set_rules('quantity', 'Component Quantity', 'required|integer');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('add_component');
        } else {
            $this->Component->insert();;
            redirect("site");
        }
    }
}

If we want to make this controller default controller for our application, we need to edit routes.php file in application/config directory

Find line

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

Replace welcome with our controller name site

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

Now, when we visit our CodeIgniter webpage, it will load our Site controller.

Next thing to do is to add new route in routes.php

$route['add'] = 'site/add';

This means that when we type

http://your_website/codeigniter/add

it will be understood as

http://your_website/codeigniter/site/add

This is optional, but can make your URLs a lot more user friendly.

 

Model

Create new model Component that we will use for communication with database, models are located in application/models directory

Component.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Component extends CI_Model
{
    function insert()
    {
        $data = array(
            'ComponentName' => $this->input->post('name'),
            'ComponentNo' => $this->input->post('quantity')
        );

        $this->db->insert('components', $data);

    }
}

Model now contains only function for inserting data to database, we’ll expand it in next tutorials.

 

View

We need to create view files that we’ll use for header and footer so we can include them in the rest of our views.

Create new directory in application/views folder, name it templates.

Add two PHP files inside templates folder

header.php

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Hardware Store</title>

    <!-- Bootstrap core CSS -->
    <link href="<?php echo base_url(); ?>style/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="<?php echo base_url(); ?>style/css/sticky-footer-navbar.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

<!-- Fixed navbar -->
<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <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="<?php echo base_url(); ?>">Hardware Store</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="<?php echo base_url(); ?>">Home</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Options <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="<?php echo base_url(); ?>add">New Component</a></li>
                    </ul>
                </li>
            </ul>
        </div><!--/.nav-collapse -->
    </div>
</nav>

footer.php

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<footer class="footer">
    <div class="container">
        <p class="text-muted"><a href="http://linuxwebzone.com">Linux Web Zone Tutorials</a></p>
    </div>
</footer>

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="<?php echo base_url(); ?>style/bootstrap/assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="<?php echo base_url(); ?>style/js/bootstrap.min.js"></script>

</body>
</html>

Now, we will create two more view files, one we’ll use in this tutorial, and another will be index page that will show all data from database which will be next tutorial.

Create files site.php and add_component.php in application/views directory

site.php

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<?php $this->load->view('templates/header'); ?>

    <!-- Begin page content -->
    <div class="container">
        <div class="page-header">
            <h1>Hardware Components</h1>
        </div>
    </div>

<?php $this->load->view('templates/footer'); ?>

add_component.php

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<?php $this->load->view('templates/header'); ?>

    <!-- Begin page content -->
    <div class="container">
        <div class="page-header">
            <h1>Add New Hardware Component</h1>
        </div>

        <div class="col-md-10">
            <?php if(validation_errors() != '') echo '<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>' . validation_errors() . '</strong></div>'; ?>

            <?php echo form_open('site/add'); ?>

            <div class="input-group input-group-lg">
                <input type="text" class="form-control" placeholder="Component Name" id="name" name="name" aria-describedby="sizing-addon1" value="<?php echo set_value('name'); ?>" autofocus>
            </div>

            <br />

            <div class="input-group input-group-lg">
                <input type="text" class="form-control" placeholder="Component Quantity" id="quantity" name="quantity" aria-describedby="sizing-addon1" value="<?php echo set_value('quantity'); ?>">
            </div>

            <br />

            <div>
                <input class="btn btn-primary btn-lg" href="#" role="button" type="submit" name="submit" value="Add" />
            </div>

            <?php echo form_close(); ?>
        </div>
    </div>



<?php $this->load->view('templates/footer'); ?>

Now, open your browser and visit your CodeIgniter page, it should look like this

CodeIgniter Site

Click on Options > New Component and it will load our page for adding new component

CodeIgniter Add Page

Fill out the form and you should be redirected to Hardware Components page.

You can now go to phpMyAdmin and check if data is inserted in database.

If data is successfully inserted, you should see it in components table

CodeIgniter Add Database

If there are no new rows in table, you shoul check your code for possible errors.


Our first lesson – CodeIgniter Insert is now complete, stay tuned for our next tutorial where we’ll be reading data from database and display it on page.

You can download complete source code from this tutorial on the link bellow

CodeIgniter Lesson 1 – Insert

Leave a Reply

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