0

This is my simple php html code.

<select id="district" name="district">
    <option value="">Select district</option>
<?php 
  $sql="SELECT * FROM district";

    $result = mysqli_query($sql);

    while($row = mysqli_fetch_array($result))
{
$district_id   = $row['district_id'] ;
$district_name = $row['district_name'];
?>
 <option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php

}
?>      
</select>

But it's not working. database is autoloaded.What will be the problem.

2
  • You can call model function in view instead of calling query here. Commented Dec 24, 2014 at 6:15
  • then why you using codeigniter Commented Dec 24, 2014 at 6:16

4 Answers 4

7

you are using direct query not with CI db instance so you will not getting db connection try in CI way

$sql ="SELECT * FROM district";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
  foreach ($query->result() as $row) {?>
     <option value="<?php echo $row->district_id;?>"><?php echo $row->district_name;?></option>
<?php }
}

or

  $this->db->from('district');
  $query = $this->db->get();
  if($query->num_rows > 0 ) {
    foreach ($query->result() as $row) {
      // do your stuff
    }
  }

Better method to work with MVC framework:- use model for db queries and return data on view via controller (do not use direct query on view)

Sign up to request clarification or add additional context in comments.

Comments

2

May be your get CI instance wirte you CI query directly

$CI =& get_instance();
$CI->load->model('modelname');
$result = $CI->modelname->functionname();

Comments

0

If you must access db directly from, view try this:

$this->load->view('view_name',["db"=>$this->db,"other_data=>"data"]);
//$this->db //CI db instance

In view you can now do:

$db->query("select * from table")->result();

Comments

-1

please try this

<select id="district" name="district">
<option value="">Select district</option>

$result = mysqli_query($sql);

while($row = $result->fetch_array())
{
 $district_id   = $row['district_id'] ;
 $district_name = $row['district_name'];
?>
  <option value="<?php echo $district_id;?>"><?php echo $district_name;?></option>
<?php } ?>      

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.