Welcome Guest, Not a member yet? Register   Sign In
Display Blog Categories
#1

[eluser]clintonbeattie[/eluser]
Hi,

I'm having problems displaying my blog categories.
My category table is called "category" and I have two fields, one "id" and the other "cat_name".

Any help welcome...

MODEL
Code:
function getAllCategories(){
        $data = array();
        //all records from the database are retrieved as an array.
        $this->db->select('cat_name');
        $this->db->from('category');
        $Q = $this->db->get();
        if ($Q->num_rows() > 0) {
        foreach ($Q-> result_array() as $row) {
            $data[] = $row;
            }
        }
        $Q-> free_result();
        return $data;
    }

CONTROLLER
Code:
function cat_nav()
    {
        $data['categories'] = $this->MBlog->getAllCategories();
        $data['secondary_content'] = 'blog_secondary_content';
        $this->load->vars($data);
        $this->load->view('template');
      }

VIEW
Code:
foreach ($categories as $key => $category) {
        echo "<p>".$category['cat_name']."</p>";
      }

ERRORS DISPLAYED
Code:
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: categories

Filename: views/blog_secondary_content.php

Line Number: 8

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/blog_secondary_content.php

Line Number: 8
#2

[eluser]Dam1an[/eluser]
First of all, not sure why you need the $key as part in the foreach look, as you never refer to the key

Try
Code:
// Model
function get_all_categories() {
    $query = $this->db->get('categories');
    return $query->num_rows() == 0 ? false : $query->result();
}

// Controller
function cat_nav() {
    $data['categories'] = $this->MBlog->get_all_categories();
    $this->load->view('template', $data);
}

// VIew
if($categories === false) {
    echo 'No categories';
} else {
    foreach($categories as $category) {
        echo $category->cat_name;
    }
}
#3

[eluser]clintonbeattie[/eluser]
Doesn't work I'm afraid. Can you tell what => means? I copied that code with $key from a book
#4

[eluser]Dam1an[/eluser]
In an array, each item has a key and a value, the key is the unique identifier, which can be a string or a number (in you're case it would just be a number, as you never set a key yourself)

Do you still get the same error?
#5

[eluser]Thorpe Obazee[/eluser]
[quote author="modelreject" date="1242505295"]Doesn't work I'm afraid. Can you tell what => means? I copied that code with $key from a book[/quote]

$key => $value as in

Array
$test['key'] = 'value';




Theme © iAndrew 2016 - Forum software by © MyBB