I'm trying to get a database query which is an object converted to an associative array, so that I can use it in the calendar class in codeigniter.
This is my model:
<?php
class Get_diary_model extends Model {
function getAllDiaries($year,$month) {
$data = $this->db->query("SELECT day AND entry FROM diary WHERE month=$month AND year=$year"); // the entries for the relevant month and year
foreach($data->result_array() as $row) { // return result as assoc array to use in calendar
echo $row['day'];
echo $row['entry'];
}
return $data;
}
}
and this is the error I get:
atal error: Cannot use object of type CI_DB_mysql_result as array in C:\wamp\www\mm\system\libraries\Calendar.php on line 219
Any ideas?
Check ou this video tutorial, it will help you -> http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-the-calendar-library/
Your model should look like this:
function getAllDiaries($year,$month)
{
$q = $this->db->query("SELECT day AND entry FROM diary WHERE month=$month AND year=$year");
if($q->num_rows() > 0):
foreach($q->result() as $row):
$data[] = $row;
endforeach;
return $data;
else:
return false;
endif;
}
and your controller:
function index($year = null, $month = null)
{
$this->load->model('Get_diary_model');
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$data['calendar'] = $this->Get_diary_model->getAllDiaries($year, $month);
}
The problem was not in your use of result_array(), more that you later return $data directly. $query = $this->db->query() then use $query->result_array() in the foreach. Then you can return $data after building it up in the foreach.
The other answer is a long-winded way of writing the following:
function getAllDiaries($year,$month)
{
$sql = "SELECT day AND entry FROM diary WHERE month=$month AND year=$year";
return $this->db->query($sql)->result();
}
But of course that will return an array of objects, not an multidimensional array.
Use below simple method,
$query = $this->db->get_where('table', array('table_id' => $id));
$queryArr = $query->result();
foreach ($queryArr[0] as $key=>$val)
{
$row[$key]=$val;
}
print_r($row); //this will give associative array
Here is the solution for CodeIgniter-3
function getAllDiaries(){
$query = $this->db->query("YOUR QUERY HERE");
return $query->result('array');
}
OR
function getAllDiaries(){
return $this->db->query("YOUR QUERY HERE")->result('array');
}
Note: result() function accept "array" or "object" as parameter. Default is "object"
Related
Hello There I need Help To Update on Vehicle Wies on Specific Dates.I'm Attaching Form image and Here is my Controller code.
public function add_vehicle_expense(Request $request)
{
$veh = array('veh_reg_num' => $request->veh_reg_num);
foreach ($veh as $data) {
print_r($request->date[$data]);
dd();
$veh = Sale_report::where('date',$request->date[$data])->where('veh_reg_num', $request->veh_reg_num[$data])->update(['diesel_qty'=> $request->qty[$data], 'diesel_rate'=> $request->rate[$data], 'diesel_amount'=> $request->total_amount[$data], 'other_expense'=> $request->other_exp[$data]]);
}
if ($veh) {
return redirect()->back()->with('Data Store Successfully');
}
//$veh = Sale_report::where('date',$request->date)->where('veh_reg_num', $request->veh_reg_num)->update(['diesel_qty'=> $request->qty, 'diesel_rate'=> $request->rate, 'diesel_amount'=> $request->total_amount, 'other_expense'=> $request->other_exp]);
/* foreach ($request->date as $reg_num => $key ) {
$s = Sale_report::where('date',$request->date[$reg_num])->where('veh_reg_num',$request->veh_reg_num[$reg_num])->first();
$s->diesel_qty = $request->qty[$reg_num];
$s->diesel_rate = $request->rate[$reg_num];
$s->diesel_amount = $request->total_amount[$reg_num];
$s->other_expense = $request->other_exp[$reg_num];
$s->update();
} */
}
I have try to Update Data by matching Each Vehicle Number with Date Some times it Show ErrorException Attempt to read property on int,ErrorException Undefined array key "data"
I have Found The Solution of this Problem.
I've use implode(',' , $request->veh_reg_num) Then I use $datas = explode() function then I use foreach() With exploded Vairable as foreach($datas as $data => $value){
match the each row that with $data array then I Update the values to data base }
I need to print $data2['hasil2'] result, but the result just print empty array Array ( ). Could anyone tell me how the correct way to passing $data1 and $semester in tampilSos function?
public function insertOrtu(){
$Semester= $_POST['Semester'];
$person=$this->session->userdata('idperson');
$data1=$this->M_Ortu->tampilIdsiswa($person);
$data2['hasil2']=$this->M_Ortu->tampilSos($data1, $Semester);
print_r($data2['hasil2']);
}
here my model
public function tampilIdsiswa($person){
$this->db->select('idsiswa');
$this->db->from('siswa a');
$this->db->join('siswa_kelas b','a.induk=b.induk','left');
$this->db->where('idperson',$person);
$data=$this->db->get();
return $data->row()->idsiswa;
}
public function tampilSos($idsiswa, $semester){
$array = array('idsiswa' => $idsiswa, 'kdSemester' => $semester, 'kdmapel'=>'sos');
$this->db->select('*');
$this->db->from('nilai_siswa a');
$this->db->join('master_nilai b','a.idnilai=b.idnilai','right');
$this->db->where($array);
$data = $this->db->get();
return $data->result();
}
I am using codeigniter and I have made a function to return name of the user. Here is the code:
$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->result_array();
$string = $data->u_name.' '.$data->u_surname;
return $string;
When I am using this function i get this error:
Message: Trying to get property of non-object and recall the line with
$string = [...]
Use foreach loop:
foreach ($data as $row)
{
echo $string = $data['u_name'].' '.$data['u_surname'];
}
You can try like this.In codeigniter,The row() returns the matched first row according to your condition in object form.
$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->row();//change here
$string = $data->u_name.' '.$data->u_surname;
//echo $string;
return $string;
for more see Codeigniter Result Sets
Try this code to return
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('u_id'=>$id));
$query=$this->db->get();
if($query->num_rows()()>0)
{
$data = $query->result();
return $data->u_name.' '.$data->u_surname;
}
This is because the function you chose to generate results for you query.
$data = $query->result_array();
result_array() returns the results in an array even if you only had one result, so when you try to $data->u_name for instance, you have this error because the array does not have that property.
You can do a foreach on $data and perform your logic or use other methods to get the result from the query like $query->row_array();
Take a look on the codeigniter documentation: Generating Query Results
I want to load all my rows of column "name" in my table "districts".
I can already read the first row but not more then that.
My Controller:
public function showdataAction()
{
$districtMapper = new Backoffice_Model_DistrictMapper();
$array = $districtMapper->read();
Zend_Debug::dump($array);
}
My DistrictMapper:
public function read()
{
$table = $this->_dbTable;
$columns = array('wijk' => 'wijk', 'coords' => 'coords', );
$select = $table->select() ->from($table, $columns) ->order('wijk ASC');
if ($row = $table->fetchRow($select)) {
return $row->toArray();
}
throw new Exception('The requested data cannot be found');
}
In my Controller I have Zend_Debug::dump($array) and the result is:
array(2) {
["wijk"] => string(10) "Binnenstad"
["coords"] => string(2186) "3.72448685517794,51.0601522198842,
0 3.72577413282654,51.0597215800093,0 3.72594328459339,
51.0600395135711,0 3.72699385985136, 51.060876600363,
0 3.72764765694006,51.0608474287073,
0 3.7281167878913,51.0605006616679,0 3.72955689560896,
51.059999738927"
}
Only the first row ... How can I can convert the read function so I can load all the rows?
public function read()
{
$table = $this->_dbTable;
$columns = array('wijk' => 'wijk', 'coords' => 'coords', );
$select = $table->select() ->from($table, $columns) ->order('wijk ASC');
//try/catch might make more sense as fetchAll() returns an object or an exception.
$result = $table->fetchAll($select)
return $result->toArray();
}
Change fetchRow() to fetchAll(). fetchRow() returns one row object or null, fetchAll() returns a rowset object (array of row objects) or an exception/fatal error.
if ($row = $table->fetchRow($select)) {
return $row->toArray();
}
change that portion of code to
return $your_database_object->fetchAll($select);
I have the following model that print_r shows Array ( [id] => 1 [cms_name] => Content Mangement System ) Currently in my controller I have $data['contentMangement'] = $this->model->function but I am unsure how to bring my above array into this.
function systemOptions($options)
{
$this->db->select($options);
$query = $this->db->get('options');
if($query->num_rows() > 0)
{
$row = $query->row_array();
$row['cms_name'];
}
print_r($row);
return $query->result_array();
}
If you want all of your options you can do this:
function systemOptions($options)
{
$this->db->select($options);
return $this->db->get('options')->result_array();// will return empty array if there are no results
}
Or if you just want the first row (which is what it looks like from your question) you can do this:
function systemOptions($options)
{
$this->db->select($options);
$result = $this->db->get('options')->result_array();
if(!empty($result))
{
return $result[0];
}else{
return null; //or false or array(), or whatever you want
}
}