I've try to get result from sql query in codeigniter with mode select all attribute but it returns a PHP error but when I specify some attribute in give the right answer but the query is too long to be written.
This 2 mode select that I've try and give different result.
First
class model_kemiskinan extends CI_Model {
..... //constructor here
function get_kemiskinan_provinsi(){
$this->tahun = "2011";
$this->kodeProv = "31";
$this->query = "select * from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;
$this->result = $this->db->query($this->query);
return $this->result->result();
}
Then the controlller pass it
public function testquery(){
$this->load->model('model_kemiskinan');
$data['hasil'] = $this->model_kemiskinan->get_kemiskinan_provinsi();
$data['main_content'] = 'test';
$this->load->view('template', $data);
}
and the view 'test' respond it with these code:
if(is_array($hasil)){
foreach ($hasil as $baris ) {
echo $baris->tahun;
echo $baris->id_provinsi;
echo "<br/>";
}
And the result is this
A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$tahun
Second
But if I change the select mode that look like this :
$this->query = "select tahun, id_provinsi from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;
It will work properly
Is there any solution about select all mode?
-Thanks before-
like the documentation ( http://ellislab.com/codeigniter/user-guide/database/examples.html ) says:
$query = $this->db->query('SELECT name, title, email FROM my_table');
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->email;
}
echo 'Total Results: ' . $query->num_rows();
you get only one row by calling result() so you need to call it by foreach:
function get_kemiskinan_provinsi(){
$this->tahun = "2011";
$this->kodeProv = "31";
$this->query = "select * from kemiskinan where id_provinsi = ".$this->kodeProv." and tahun = ".$this->tahun;
$this->result = $this->db->query($this->query);
$res = array();
foreach ($this->result->result() as $row)
{
$res[] = $row;
}
return $res;
}
Please recognize that the fields in the result object are case sensitive! If you have a field named "Tahun" in your db then "select tahun ..." will work in mysql and will give you an object where you can access $res->tahun.
If you do "select * ...." then you can only access it like this: $res->Tahun (with capial T)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.