Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Mysql Result Object to Associative Array (CodeIgniter)

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?

like image 367
Robimp Avatar asked Sep 16 '10 11:09

Robimp


3 Answers

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);
}
like image 109
Christophe Avatar answered Nov 10 '22 20:11

Christophe


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.

like image 26
Phil Sturgeon Avatar answered Nov 10 '22 18:11

Phil Sturgeon


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
like image 2
Kiran Avatar answered Nov 10 '22 18:11

Kiran