-2

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

Im trying to get my database query to work within my model for codeignuter but whenever i try to load the page it says

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: models/model_get.php

Line Number: 21

    function getLinks(){
        $q = $this->db->query("SELECT * FROM links ORDER BY link_name ASC");
        if($q->num_rows() > 0){
            foreach($q->result() as $row){
                $data[] = $row;
            }
        }
        return $data;   (this is line 21)
    }
}

I also have another query that's in the same model with the data variable and it works just fine, i have also tired changing the variable name but that did not work either. Any suggestions?

Community
  • 1
  • 1
user1537210
  • 15
  • 1
  • 7

2 Answers2

2

It's trying to return $data right there on :21 but if there were no rows returned from the query, $data is not yet defined.

$data = array();

should be the first line of this function.

Emery King
  • 3,550
  • 23
  • 34
2

You should define $data before the if conditional - if $q->num_rows == 0 then $data will be undefined.

It's as simple as $data = array(); before the conditional.

sevenseacat
  • 24,699
  • 6
  • 63
  • 88