My stackoverflow answer #9

by krike in Other / Stackoverflow answers on 29 Nov 2010


Each week I feature one of my answers on stackoverflow hoping it might help other people.

The question

This weeks question by Robimp: 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:

Fatal error: Cannot use object of type CI_DB_mysql_result as array in C:wampwwwmmsystemlibrariesCalendar.php on line 219

Any ideas?

My anwser

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);
}

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.