I need to get the last 5 records of a table sorted by their ID, I want to know if my query is ok:
public function getLastProductos(){
$this->db->select("p.*, c.nombre as categoria");
$this->db->from("productos p");
$this->db->join("categorias c","p.categoria_id = c.id");
$this->db->order_by("id","desc");
$this->db->limit("5");
$resultados = $this->db->get();
return $resultados->result();
}
and how can I pass it to the controller and then display it in a view?
This is my driver to list a view, but how can I integrate it here, to show it in my view?
public function index()
{
$data = array(
'permisos' => $this->permisos,
'productos' => $this->Productos_model->getProductos()
);
$this->load->view("layouts/header");
$this->load->view("layouts/aside");
$this->load->view("admin/productos/list",$data);
$this->load->view("layouts/footer");
}
the function of getProductos is another one in which you ready the products of my table, which is this:
public function getProductos(){
$this->db->select("p.*,c.nombre as categoria");
$this->db->from("productos p");
$this->db->join("categorias c","p.categoria_id = c.id");
$this->db->where("p.estado","1");
$resultados = $this->db->get();
return $resultados->result();
}
Ready, after making the query, like this:
public function getLastProductos(){
$this->db->select("p.*, c.nombre as categoria");
$this->db->from("productos p");
$this->db->join("categorias c","p.categoria_id = c.id");
$this->db->order_by('id',"desc");
$this->db->limit(5);
$resultados = $this->db->get();
return $resultados->result();
}
Place the function in the controller:
public function index()
{
$data = array(
'permisos' => $this->permisos,
'productos' => $this->Productos_model->getProductos(),
'productoslast' => $this->Productos_model->getLastProductos()
);
$this->load->view("layouts/header");
$this->load->view("layouts/aside");
$this->load->view("admin/productos/list",$data);
$this->load->view("layouts/footer");
}
To finally get the query already ordered in the view as follows:
<!-- ./col -->
<div class="row">
<div class="col-md-12">
<div> <strong>Ultimos 5 Productos Agregados</strong></div>
<div class="col-xs-12">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Codigo</th>
<th>Nombre</th>
<th>Categoria</th>
</tr>
</thead>
<tbody>
<?php if(!empty($productoslast)):?>
<?php foreach($productoslast as $producto):?>
<tr>
<td><?php echo $producto->id;?></td>
<td><?php echo $producto->codigo;?></td>
<td><?php echo $producto->nombre;?></td>
<td><?php echo $producto->categoria;?></td>
</tr>
<?php endforeach;?>
<?php endif;?>
</tbody>
</table>
</div>
<!-- /.row -->