[eluser]Zorancho[/eluser]
I wanted to share my Model library, but i was helpless in finding a way to upload it there, so if anyone is better in this, please help me move this thing to the wiki.
Here it is:
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//system/application/libraries/MY_Model.php
class MY_Model extends Model
{
function MY_Model()
{
parent::Model();
$this->load->database();
}
function obj_more($sql)
{
$rows = array();
$q = $this->db->query($sql);
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$rows[] = $row;
}
$q->free_result();
return $rows;
}
return FALSE;
}
function obj_one($sql)
{
$q = $this->db->query($sql);
if($q->num_rows() == 1)
{
$row = $q->row();
$q->free_result();
return $row;
}
return FALSE;
}
function arr_more($sql)
{
$rows = array();
$q = $this->db->query($sql);
if($q->num_rows() > 0)
{
foreach($q->result_array() as $row)
{
$rows[] = $row;
}
$q->free_result();
return $rows;
}
return FALSE;
}
function arr_one($sql)
{
$q = $this->db->query($sql);
if($q->num_rows() == 1)
{
$row = $q->row_array();
$q->free_result();
return $row;
}
return FALSE;
}
}
Using this model is quite simple, cause in your models you can do this:
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MProducts extends MY_Model
{
function MProducts()
{
parent::MY_Model();
}
//Note: Don't forget the usual escaping of the data
function get_products_obj($category_id)
{
$sql = "SELECT * FROM product WHERE category_id = ".$category_id;
return $this->obj_more($sql);
}
function get_product_obj($id)
{
$sql = "SELECT * FROM product WHERE $id = ".$id;
return $this->obj_one($sql);
}
function get_products_arr($category_id)
{
$sql = "SELECT * FROM product WHERE category_id = ".$category_id;
return $this->arr_more($sql);
}
function get_product_arr($id)
{
$sql = "SELECT * FROM product WHERE $id = ".$id;
return $this->arr_one($sql);
}
}
The good thing about this library is the size, it's small and it saves you writing lots of code, also it returns either the row(s) as object(s) or array(s) on success and it returns FALSE on failure.
Using this in your controller function:
Code:
function show_products($category_id)
{
$this->load->model('MProducts');
$data['products_obj'] = $this->MProducts->get_products_obj($category_id);
$this->load->view('products', $data);
}
And in the view:
Code:
<?php foreach($products_obj as $p): ?>
<p><?php echo $p->id; ?></p>
<p><?php echo $p->name; ?></p>
<?php endforeach; ?>