Skip to content
Advertisement

How to fetch Data from another table and show on single table in PHP Codeigniter?

I need help, I have 2 tables Client and Product. I want to fetch data from Product Table on basis of Client Table and show it as whole.

productTable
productId     productName      productPrice
1             Abc              100
2             Bcd              200
3             Cde              300

clientTable
clientId        productNameId     clientName
4               2                 A
5               3                 B
6               1                 C

I want the table to show the record as:

Client Name             Product Name
A                       Bcd
B                       Cde
C                       Abc

How can I show them using MVC CI.

Model

class Client_model extends CI_model
{
    function All()
    {
        return $client = $this->db->get('client')->result_array();
    }
}

Controller

class Client extends CI_Controller
    public function index()
    {
        $this->load->model('Client_model');
        
        $invoice = $this->Client_model->All();
        $data = array();
        $data['client'] = $client;
        $this->load->view('admin/ViewClient', $data);
    }
}

Advertisement

Answer

Client Controller Code:-

class Client extends CI_Controller
    public function index()
    {
        $this->load->model('Client_model');
        
        $data['clientData']  = $this->Client_model->All();
        
        
        $this->load->view('admin/ViewClient', $data);
    }
}

Client_model Model Code:-

class Client_model extends CI_model
{
    function All()
    {
        return $client = $this->db->get('client')->result_array();
    }
}

ViewClient View Page:-

<table>
<thead>
    <tr>
        <th>S.NO</th>
        <th>client Name</th>
        <th>Product Name</th>
   </tr>
</thead>

<tbody>
<?php if(!empty($clientData)) { 
    $count=1;
foreach($clientData as $client){ 
                
?>
<tr>
    <td><?php echo $count; ?></td>
    <td><?php echo $client['clientName']; ?></td>
    <td><?php 
 $pid =  $client['productNameId'];
$pdata = $this->db->get_where('productTable',array('productId '=>$pid))->row();
echo  $pdata->productName; ?>
    </td>
    
    </tr>
     <?php $count++;
    } } 
    ?>
    </tbody>

    </table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement