Topic outline

  • CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. 

  • Setting Up

    1) Set up a database

    To set up a database you can still use phpmyadmin which is located at http://localhost/phpmyadmin/.  If you use the same access details as setup in school then this will make transferring files between school and home easier.   The best way to set up a database is to use the Privileges tab at the top and when you create a new user to Create database with same name and grant all privileges at the same time.

    PHPMyAdmin for Projects

     

    2) Where to put your files.

    Now we are using the Codeigniter system so depending on whether you have bought all your files from school or not you may need to download the system again.  I’m going to download a fresh copy of Codeigniter and set it up to work from home.   Clicking on that link downloads the lastest version on Codeigniter as a zip file.   You need to extract that file into the Root of your XAMPP installation but where is that I hear you ask!!.   

    You need to put your files inside the htdocs folder of your installation.  I installed my XAMPP atC:Usersdaviescxampp  and therefore I will place my files inside C:Usersdaviescxampphtdocs.  So my htdocs folder now looks like this with the CodeIgniter_2.0.0 folder at the bottom but I’m going to rename this folder to Project

    File Location for project 

    3) Showing that CodeIgniter now works

    Now providing you haven’t missed a beat or made a mistake it should be working.  One mistake I made was that when I extracted the CodeIgniter files I left them in a sub-folder so I had project/CodeIgniter_2.0.0, once I moved all the files into just the project folder I was able to see the screen below.

     

     CI Working

  • Create Records

    This section will show you how to create a new record/object using Codeigniter.

    ci_insertform

    In this example I am using a table called news with 3 fields ( id, title, body). If you haven’t already set up your database you will need to do so NOW! Database login details go in config/database.php and I recommend phpmyadmin for management etc.

    CREATE TABLE `databaseName`.`blog` (
      `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
      `title` VARCHAR( 100 ) NOT NULL ,
      `body` TEXT NOT NULL
    ) ENGINE = MYISAM ;

    1)  Create a new_object function in your controller with appropriate commenting.

        /**
        * @brief New Object Function.
        *
        * Calls New Object Form from the Class View folder.
        *
        * @see views/blog/new_object.php
        **/
        function new_object() {
            $this->load->view('blog/new_object');
        }

    CREATE A CORRESPONDING VIEW WITH A FORM

    Before starting this section make sure you have added the form helper to the autoload config file

    <?php
    /** @file views/blog/new_object.php
    * @brief Create New Object Form.
    * 
    * @section DESCRIPTION
    * Simple Create form for new blog posts, requires title
    * and body fields and calls Blog::insert_object() on submission.
    **/
    ?>
     
    <html>
    	<head>
    		<title><?php echo $title; ?></title>
    	</head>
     
    	<body>
     
    		<h1><?php echo $heading; ?></h1>
     
    		<?php echo form_open('blog/insert_object'); ?> 
     
    		<!-- Start a new table -->
    		<table>
     
    		<!-- For each field create the input fields you require. -->
    		<tbody>
    		<tr>
    		<th>Title:</th>
    		<td><input type="text" name="title" /></td>
    		</tr>
     
    		<tr>
    		<th>Body:</th>
    		<td><textarea name="body" rows="10"></textarea></td>
    		</tr>
     
    		<!-- End the table -->
    		</table>
     
    		<!-- Add a form submit button -->
    		<input type="submit" alt="Save" name="submit" />
     
    		<!-- End the form-->
    		</form>
     
    	</body>
    </html>

    CHECK THE FORM IS OK

    You should now be able to view the form using your Browser the following URL:

    http://daviesc.big-blue.local/codei/index.php/blog/new_object

    INSERT THE RECORD INTO THE DATABASE.

    If you create the following function in your Controller you should now be in a position to test your insert routine.

        /**
        * @brief Insert Object Function.
        *
        * Inserts a new object into the database and redirects to the index page.
        *
        * @todo validate the inputs from the form.
        **/
        function insert_object () {
     
    		//Set up an array with all your form variables in it.
    		$data = array(
    			'title' => $this->input->post('title'),
    			'body' => $this->input->post('body'),
    		);
     
    		//Insert record into the database
    		$this->db->insert('blog', $data);
     
    		//Redirect the page
    		redirect('blog/index');
     
        }

     

  • Read

    This section will show you how to read records from the database.  each controller has a default function called index and this should always relate to a default view of all records which you will often need anyway.  If you then need other filtered or ordered views you can create them as different functions (but if you want to still use the same view).

    1) Create an index function in your controller

        /**
        * @brief Index Function.
        *
        * List view of the Blog.
        * Gets the data from the Blog table.
        *
        * @see views/blog/new_object.php
        **/
        public function index() 
        {
     
        	//Some key variables.
        	$data['title'] = "My Blog";
        	$data['heading'] = "All Posts";
     
     
        	//Get the database results
        	$data['query'] = $this->db->get('blog');
     
        	//Pass results and load view.
            $this->load->view('blog/index',$data);
        }

    2) Create a corresponding view

    Once you’ve got the function you will need a view to show the data.   This will need a loop to go through all the records and a table to structure them in.  Note how I’ve created a link around the post title to link to a detailed view and the link at the bottom for new items.

    <?php
    /** @file views/blog/index.php
    * @brief Blog List View.
    * 
    * @section DESCRIPTION
    * List view for all Blog Items.
    **/
    ?>
     
    <html>
    	<head>
    		<title><?php echo $title; ?></title>
    	</head>
     
    	<body>
     
    		<h1><?php echo $heading; ?></h1>
     
    		<?php foreach($query->result() as $row): ?>
     
    			<h3><?php echo anchor('/blog/detail/'.$row->id,$row->title); ?></h3>
    			<p><?php echo $row->body; ?></p>
     
    		<?php endforeach; ?>
     
     
    		<?php echo anchor('blog/new_object/','New Blog Post?'); ?>
     
    	</body>
    </html>

  • Update records

    Updating is the third step in CRUD and allows us to change data stored in the database.

    1) In the index [list] view create a link to the detail [update] function in the controller

    You need to be able to call a record from a list view so add an anchor that includes the ID field using: echo anchor('/news/detail/'.$row->id,$row->title);
    which should give you a hyperlink like this: http://cims.local/index.php/news/detail/1

    If you get an error message regarding anchor then go to config/autoload.php and add url to theautoload['helper'] array.

    2) Add the function to the controller

    In the controller you need to add a new function that will recieve the call from step 1.

    /* Function that will allow us to update our database row */
    function detail () {
     
    //Get the third part of the url where the ID field is.
    $id = $this->uri->segment(3);
     
    //Get records from the database where the ID field matches.
    $this->db->where('id',$id);
    $query = $this->db->get('news');
     
    //Get the first row returned
    $data['query'] = $query->row();
     
    //Load the detail view
    $this->load->view('news/detail',$data);
     
    }

    3) Create a new view that will present a single persons data in a form for updating.

    When deciding the name for this section you need to refer to the view called in the load->view on line 15 above.

    For this next section you need to make sure you are loading the form helper in config/autoload.php.

    <!-- Open a new form and set a hidden id field -->
     
     
    <!-- Start a new table -->
    <table>
     
    <!-- For each field create the input fields you require. -->
     
    <tbody>
    <tr>
    <th>Title:</th>
     
    <td></td>
    </tr>
     
    <tr>
    <th>Body:</th>
     
    <td></td></tr>
     
    <!-- End the table -->
    </table>
     
    <!-- Add a form submit button -->
    <input type="submit" alt="Save" name="submit" />
     
     
    <!-- End the form-->
    </form>

    4) Responding to a SUBMIT click

    When someone clicks on submit you need to respond to it. Looking at line 3 on the previous code insert you can see that the form has an action response that calls news/update_object.  Therefore we need to create a function in the news controller called update_object.

    function update_object () {
     
    //Set up an array with all your form variables in it.
    $data = array(
    'title' => $this->input->post('title'),
    'body' => $this->input->post('body'),
    );
     
    //Update the database where something matches that ID
    $this->db->where('id', $this->input->post('id'));
    $this->db->update('news', $data);
     
    //Redirect the page
    redirect('news/index');
     
    }

     

  • Delete

    The following code excerpt shows you how to delete records with some form of confirmation before hand on CodeIgniter.

    Edit your form so the submit button has a second button underneath with a delete value.

    <!-- Add a form submit and form delete button -->
    <input type="submit" alt="Save" name="submit" value="submit" />
    <input type="submit" alt="Save" name="submit" value="delete" onclick="return confirm('Are you sure you want to delete this?');"/>

    Update the form action function in your controller so that it tests to see which button was pressed.

    //Delete the record
    if ($this->input->post('submit') == 'delete') {   
      //Delete stuff goes here
    }
     
    //Update record into the database
    else {  
      //Update stuff goes here
    }