ALFIE ALFIE - 1 month ago 10
MySQL Question

Getting a drop down list from a database in CodeIgniter

I am new to CodeIgniter and I have been trying to populate the drop down list on the view page with data from the database with no success. I tried using the recomendations from this question but the drop down is still empty (display data from database to dropdown CodeIgniter)

Here is my view:

<label>City</label>
<select class="form-control>
<option value="">All</option>
<?php
foreach($groups as $city)
{
echo '<option value="'.$city['cityidd'].'">'.$city['city'].'</option>';
}
?>
</select> <br/>


Here is my controller:

<?php
class Main_controller extends CI_Controller
{

function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
}

public function index()
{
$this->load->helper('form');
$this->load->view('supplier_add');
}
}


Here is my model:

class Site_model extends CI_Model
{

public function __construct()
{
/* Call the Model constructor */
parent::__construct();
}
function getAllGroups()
{

$query = $this->db->query('SELECT city FROM citys');


return $query->result();

}
}


The table name is "citys" then the corresponding column heads are "cityidd" and "city"

Answer

There are several issue found there. Make changes as below

 function __construct(){ 
    parent::__construct(); 
    $this->load->helper('url');
    $this->load_model('Site_model');
    $this->load->database(); 
} 
public function index(){ 
  $this->load->helper('form');
  $data['groups'] = $this->site_model->getAllGroups();
  $this->load->view('supplier_add',$data); 
} 

Finally model

function getAllGroups(){
    $query = $this->db->query('SELECT cityidd,city FROM citys');
    return $query->result_array();
}

and now test

Comments