Create Data to Database with Active Record in CodeIgniter Framework


Create new database named learn_codeigniter_with_real_apps. This database have 1 table: Product table.

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` double NOT NULL,
  `quantity` int(11) NOT NULL,
  `description` text NOT NULL,
  `status` tinyint(1) NOT NULL,
  `photo` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 1', 2, 5, 'Description 1', 0, 'thumb1.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 2', 7, 3, 'Description 2', 1, 'thumb2.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 3', 2, 7, 'Description 3', 1, 'thumb3.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 4', 3, 8, 'Description 4', 1, 'thumb1.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 5', 8, 2, 'Description 5', 1, 'thumb2.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 6', 9, 11, 'Description 6', 1, 'thumb3.gif');

Structure of Product Table

Data of Product Table




Create new folder named assets in root project. In this folder, create new folders as below:

Create new folder named images in assets folder. Copy images need to use in project to images folder.

In CodeIgniter Project, Open config.php file in config folder. Set value for base_url config as below:

$config['base_url'] = 'http://localhost:9092/LearnCodeIgniterWithRealApps/';

In CodeIgniter Project, Open autoload.php file in config folder. Add database library to libraries config as below:

$autoload['libraries'] = array('database', 'form_validation');




In CodeIgniter Project, Open autoload.php file in config folder. Add url, form and file helpers to helper config as below:

$autoload['helper'] = array('url', 'form', 'file');

In CodeIgniter Project, Open database.php file in config folder. Add values as below connect to database:

$db['default'] = array(
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '123456',
	'database' => 'learn_codeigniter_with_real_apps'
);

Create new PHP file named product_model.php in models folder as below:

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

class Product_model extends CI_Model
{

    function findAll()
    {
        return $this->db->get('product')->result();
    }

    function create($product = array())
    {
        $this->db->insert('product', $product);
    }

}

In CodeIgniter Project, Open autoload.php file in config folder and set value for model config as below:

$autoload['model'] = array('product_model' => 'productModel');




Create new PHP file named product.php in controllers folder as below:

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

class Product extends CI_Controller
{

    public function index()
    {
        $data['products'] = $this->productModel->findAll();
        $this->load->view('product/index', $data);
    }

    public function add()
    {
        $this->load->view('product/add');
    }

    public function process_add()
    {
        $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[1]|max_length[50]');
        $this->form_validation->set_rules('price', 'Price', 'trim|required|numeric|greater_than[0]');
        $this->form_validation->set_rules('quantity', 'Quantity', 'trim|required|integer|greater_than[0]');
        $this->form_validation->set_rules('description', 'Description', 'trim|required');
        $this->form_validation->set_rules('photo', 'Photo', 'callback_file_check');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('product/add');
        } else {
            $config['upload_path'] = './assets/images/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '1024';
            $config['encrypt_name'] = TRUE;
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('photo')) {
                $photoInfo = $this->upload->data();
                $_POST['photo'] = $photoInfo['file_name'];
                $_POST['status'] = isset($_POST['status']);
                $this->productModel->create($_POST);
                redirect('product');
            } else {
                $data['error_msg'] = $this->upload->display_errors();
                $this->load->view('product/add', $data);
            }
        }
    }

    function file_check()
    {
        $allowed_mime_type_arr = array(
            'image/gif',
            'image/jpeg',
            'image/jpg',
            'image/png'
        );
        $mime = get_mime_by_extension($_FILES['photo']['name']);
        if (isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != "") {
            if (in_array($mime, $allowed_mime_type_arr)) {
                return true;
            } else {
                $this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
                return false;
            }
        } else {
            $this->form_validation->set_message('file_check', 'Please choose a file to upload.');
            return false;
        }
    }
}




In CodeIgniter Project, Open routes.php file in config folder. Set value for default_controller as below:

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

Create new folder named demo in views folder. In this folder, create new views as below:

Create new PHP file named index.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Product List</title>
	</head>
	<body>

		<h3>Product List</h3>
		<a href="<?php echo site_url('product/add'); ?>">Add Product</a>
        <table border="1" cellpadding="2" cellspacing="2">
        	<tr>
        		<th>Id</th>
        		<th>Name</th>
        		<th>Photo</th>
        		<th>Status</th>
        		<th>Description</th>
        		<th>Price</th>
        		<th>Quantity</th>
        		<th>Sub Total</th>
        	</tr>
        	<?php foreach ($products as $product) { ?>
        		<tr>
        			<td><?php echo $product->id; ?></td>
        			<td><?php echo $product->name; ?></td>
        			<td><img src="<?php echo base_url(); ?>assets/images/<?php echo $product->photo; ?>" width="50"></td>
        			<td><?php echo $product->status ? 'active' : 'inactive'; ?></td>
        			<td><?php echo $product->description; ?></td>
        			<td><?php echo $product->price; ?></td>
        			<td><?php echo $product->quantity; ?></td>
        			<td><?php echo $product->price * $product->quantity; ?></td>
        		</tr>
        	<?php } ?>
        </table>

	</body>
</html>

Create new PHP file named add.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Add Product</title>
		<style type="text/css">
		  .error {
		      color: red;
		  }
		</style>
	</head>
	<body>

		<h3>Add Product</h3>
        <?php echo form_open_multipart('product/process_add'); ?>
        <table cellpadding="2" cellspacing="2">
        	<tr>
        		<td>Name</td>
        		<td>
        			<input type="text" name="name" value="<?php echo set_value('name'); ?>">
        		</td>
        		<td>
        			<?php echo form_error('name', '<span class="error">', '</span>'); ?>
        		</td>
        	</tr>
        	<tr>
        		<td>Price</td>
        		<td>
        			<input type="text" name="price" value="<?php echo set_value('price'); ?>">
        		</td>
        		<td>
        			<?php echo form_error('price', '<span class="error">', '</span>'); ?>
        		</td>
        	</tr>
        	<tr>
        		<td>Quantity</td>
        		<td>
        			<input type="text" name="quantity" value="<?php echo set_value('quantity'); ?>">
        		</td>
        		<td>
        			<?php echo form_error('quantity', '<span class="error">', '</span>'); ?>
        		</td>
        	</tr>
        	<tr>
        		<td valign="top">Description</td>
        		<td>
        			<textarea rows="5" cols="20" name="description"><?php echo set_value('description'); ?></textarea>
        		</td>
        		<td valign="top">
        			<?php echo form_error('description', '<span class="error">', '</span>'); ?>
        		</td>
        	</tr>
        	<tr>
        		<td>Status</td>
        		<td>
        			<input type="checkbox" name="status">
        		</td>

        	</tr>
        	<tr>
        		<td>Photo</td>
        		<td>
        			<input type="file" name="photo" accept="image/*">
        		</td>
        		<td>
        			<?php echo form_error('photo', '<span class="error">', '</span>'); ?>
        			<span class="error"><?php echo isset($error_msg) ? $error_msg : ''; ?></span>
        		</td>
        	</tr>
        	<tr>
        		<td>&nbsp;</td>
        		<td>
        			<input type="submit" value="Save">
        		</td>
        	</tr>
        </table>
        <?php echo form_close(); ?>

	</body>
</html>




Access index action in Demo controller with following url: http://localhost:9092/LearnCodeIgniterWithRealApps/product/index

Output

Click Add Product link open add product form

Output

Click Save button submit form to process_add action in Product controller with invalid data as below:

Output

Click Save button submit form to process_add action in Product controller with valid data

Output

I recommend you refer to the books below to learn more about the knowledge in this article: