Book Image

CodeIgniter 2 Cookbook

By : Robert Foster
Book Image

CodeIgniter 2 Cookbook

By: Robert Foster

Overview of this book

As a developer, there are going to be times when you'll need a quick and easy solution to a coding problem. CodeIgniter is a powerful open source PHP framework which allows you to build simple yet powerful full-feature web applications. CodeIgniter 2 Cookbook will give you quick access to practical recipes and useful code snippets which you can add directly into your CodeIgniter application to get the job done. It contains over 80 ready-to-use recipes that you can quickly refer to within your CodeIgniter application or project.This book is your complete guide to creating fully functioning PHP web applications, full of easy-to-follow recipes that will aid you in any aspect of developing with CodeIgniter. CodeIgniter 2 Cookbook takes you from the basics of CodeIgniter, through e-commerce features for your applications, and ends by helping you ensure that your environment is secure for your users and SEO friendly to draw in customers. Starting with installation and setup, CodeIgniter 2 Cookbook provides quick solutions to programming problems that you can directly include in your own projects. You will be moving through databases, EU Cookie Law, caching, and everything else in-between with useful, ready-to-go recipes. You will look at image manipulation using the Image Manipulation library, user management (building a simple CRUD interface), switching languages on the fly according to the user preference, caching content to reduce server load, and much more.
Table of Contents (18 chapters)
CodeIgniter 2 Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Finding the last insert id


Returning the Primary Key of the last inserted row can be useful in instances where you may wish to write data to more than one table and whose data may be related via the keys. CodeIgniter provides support for returning the last inserted key.

How to do it...

  1. Add or adapt the following code into a model:

      function insert($data) { 
        if ($this->db->insert($data, 'table_name')) { 
          return $this->db->last_id();
        } else { 
      return false; 
      } 
    } 

How it works...

Take a look at the lines in bold. We test for the returned value of $this->db->insert($data);, which will return true if successful and false if there was an error. If the returned value is true, we grab the Primary Key of the last inserted record for this connection; this value along with return $this->db->insert_id();is returned from the model to the code that called the function. If the database insert was unsuccessful, it would return false. You can adapt the above recipe...