-5

I have an error Undefined variable return data.

<?php
function getData() {

        $query = "SELECT * FROM `$this->tablename` ORDER BY `id` DESC";

        if(!$sql = mysql_query($query))
        {
            echo mysql_errno();
        }
        else
        {
            $num = mysql_num_rows($sql);           
            if($num > 0)
            {
                for($i = 0; $i < $num; $i++)
                {
                    $data[$i] = mysql_fetch_array($sql);
                }                              
            }
        }        
        return $data;
    }
?>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Huy Nguyen
  • 1
  • 1
  • 1
  • 1
    The error message is pretty clear? – PeeHaa Oct 02 '15 at 08:11
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – vaso123 Oct 02 '15 at 08:46
  • Initialize a `$data = array();` at the begining of your function. Maybe there are no rows, so `$data` wont created. – vaso123 Oct 02 '15 at 08:48

2 Answers2

0

Define $data outside of the for loop.

function getData() {
    $query = "SELECT * FROM `$this->tablename` ORDER BY `id` DESC";
    $data = array();

    if(!$sql = mysql_query($query))
...

PS: Stop using mysql_* functions. Switch to either MySQLi or PDO.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

The problem is pretty clear. $data is not initialized properly under specific circumstances:

  1. When the if statement "if(!$sql = mysql_query($query))" is true $data is never set
  2. When the if statement "if($num > 0)" is false (aka $num <= 0) $data is never set.

Thus you get a notice that data is undefined as it only gets set if the first if is false and the second if is true.

To correct this and get rid of the message you need to initialize $data at the beginning of the function.

Thomas
  • 2,886
  • 3
  • 34
  • 78