I am try to run a query in CodeIgniter model. It's working, but when I echo model function query is like below.
SELECT * FROM `table1` WHERE `id` = '17'
SELECT * FROM `table1` WHERE `id` = '20'
SELECT * FROM `table1` WHERE `id` = '21'
SELECT * FROM `table1` WHERE `id` = '22'
SELECT * FROM `table1` WHERE `id` = '23'
My model function is given below
function get_quick_navi_menu($q_code)
{
$this->db->select("*");
$this->db->where('q_id',$q_code);
$this->db->from("table0");
$q = $this->db->get();
//echo $this->db->last_query();
$final = array();
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row) {
$this->db->select("*");
$this->db->from("table1");
$this->db->where("id",$row->id);
$q = $this->db->get();
echo $this->db->last_query();
if ($q->num_rows() > 0) {
$row->children = $q->result();
}
array_push($final, $row);
}
}
I want to run query like below
SELECT * FROM `table1` WHERE `id` = '17,18,19..'
Table Structure
Table0
id q_id value1
1 2 4
2 2 5
3 2 6
Table1
t1_id id value1 value2
1 1 2 2
2 2 5 6
3 3 8 12
View
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1" style="margin-left: 1px; opacity: .9;">
<?php foreach ($menus as $menu) { ?>
<li class="dropdown-submenu"><a href="#" class="pan-btn" data-look="<?php echo $menu->sceneid;?>"><?php echo $menu->title;?></a>
<ul class="dropdown-menu">
<?php
if (isset($menu->children)) {
foreach ($menu->children as $child) { ?>
<li><a href="#" class="pan-btn" data-look="<?php echo $child->menu_scene;?>"><?php echo $child->menu_item;?></a></li>
<?php }
}
?>
</ul>
</li>
<?php } ?>
</ul>
Controller
$menus = $this->Home_model->get_quick_navi_menu($q_code);
$data = array('menus' => $menus);
Required Output:
Selecting value1 and value2 from table1 according to id from table0.
Get all ids
in an array name here ids and use where_in
outside the loop
public function get_quick_navi_menu($q_code)
{
$this->db->select("*");
$this->db->where('q_id',$q_code);
$this->db->from("table0");
$q = $this->db->get();
$final = array();
if ($q->num_rows() > 0)
{
foreach ($q->result() as $key => $row)
{
$ids[$key] = $row->id;
$data[$key] = $row;
}
$this->db->select("*");
$this->db->from("table1");
$this->db->where_in("id",$ids);
$q = $this->db->get();
//echo $this->db->last_query();
if ($q->num_rows() > 0)
{
if ( ! empty($data))
{
foreach ($data as $key => $item)
{
$item->children = $q->result();
$final[] = $item;
}
}
}
}
return $final;
/*print_r($final);*/
}
In your controller class:
make sure you have loaded your model and database in controller or in autoload.php
$q_code = 'q_code_value';
$data['menus'] =$this->Home_model->get_quick_navi_menu($q_code);
/* pass the $data in the view like this*/
$this->load->view('your_view_file_path',$data);
In your view :
<div><?php print_r($records);?></div>
For more : https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data