-1

i am newbie to codeigniter my city table structure is like

id,name,state_id

Now in view i get all data of city but i wants to also print state name.but in city table i have only state id.so how can i get state name in view

This is My controller.

public function city(){
        $query = "SELECT * FROM ".CITYTABLE." ORDER BY name ASC";
        $citydata = $this->masterModel->_get_data("",$query);
        $this->create_template('manage-city', 'admin',compact('citydata'));
}

And my view is like

<tbody>
  <?php
    $i=1;
    foreach ($citydata as $value) { 
      if($value->status == 1){
        $status = "<span class='label label-success'>Active<span>";
      }else{
        $status = "<span class='label label-warning'>Deactive<span>";
      }
  ?>
  <tr>
    <th scope="row"><?= $i++ ?></th>
    <td><?= ucfirst($value->name) ?></td>
    <td><?= $value->state_id ?></td>//HEREEEEEEEEEEE IS I WANT TO SHOW NAME OF STATE/*****/
    <td><?= $status ?></td>
    <td>
      <?php echo anchor("master/edit_city/{$value->id}","<i class='fa fa-pencil'></i> Edit",['class'=>"btn btn-link"]) ?>
      <span class="rmv-city" data-state="<?=$value->id?>"><i class="fa fa-trash"></i> Delete</span>
    </td>
  </tr>
  <?php } ?>
</tbody>

Here is my Schema

Pradeep
  • 9,667
  • 13
  • 27
  • 34
Holy Coder
  • 31
  • 9

3 Answers3

1

If you have a state table like

Table Name: states 
Fields : state_id, state_name
//City tbl
Table Name: city
Fields: id,name,state_id

You can use join the two tables like,

public function city(){
   $query = "SELECT c.id, c.name, s.state_name FROM city c join states s
             on c.state_id = s.state_id ORDER BY c.name ASC";

  $citydata = $this->masterModel->_get_data("",$query);

  $this->create_template('manage-city', 'admin',compact('citydata'));
}

But, you have to follow the standard codeigniter query.

Holy Coder
  • 31
  • 9
1

Try with this code :

Join with m_state table with m_city like this : (better use query builder class to get the results)

public function city()
{
    $sql = "SELECT `m_city`.*, `m_state`.`name` as `state_name` 
            FROM `m_city` 
            JOIN `m_state` 
            ON `m_state`.`id` = `m_city`.`state_id` 
            ORDER BY `m_city`.`name` ASC";

    $citydata = $this->masterModel->_get_data("",$sql);
    $this->create_template('manage-city', 'admin',compact('citydata'));
}

For more : https://www.codeigniter.com/user_guide/database/query_builder.html

Pradeep
  • 9,667
  • 13
  • 27
  • 34
0

Use Following Query

SELECT m_city.id,m_city.name,m_state.name AS state_name
FROM m_city
JOIN m_state ON m_city.state_id=m_state.id
TarangP
  • 2,711
  • 5
  • 20
  • 41