tags:

views:

23

answers:

1

The following works:

$user_list = new user_list();
$all_users_list = $user_list->getAllUsers();

The following doesn't work and I'm unsure as to why it doesn't:

$user_list = new user_list();

The above returns:

 Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given on line 59

Classes for reference:

class dbo extends mysqli {

    public function __construct(){
        require('config_db.inc.php');
        parent::__construct($db_host, $db_user, $db_pass, $db_name);

        if (mysqli_connect_error()) {
            die("Connect Error: (".mysqli_connect_errno().") - ".mysqli_connect_error());
        }
    }



}

class user_list extends user {

    var $table_name = "cms_users";  

    function __construct($group = "") {
        if ($group == "") {
            return $this->getAllUsers();
        } else {
            $this->getUsersFromGroup($group);
            return $this->result;
        }
    }   

    function getAllUsers() {
        $dbh = new dbo();
        $sql = "SELECT * FROM {$this->table_name}";
        return $dbh->query($sql);
    }

    function getUsersFromGroup($group) {
        $dbh = new dbo();
        $sql = "SELECT * FROM {$this->table_name} WHERE group=$group";
        return $dbh->query($sql);
    }


}
+1  A: 

The problem is your reuse of the variable name $user_list for different purposes:

$user_list = new user_list();
// $user_list is now an object

$user_list = $user_list->getAllUsers();
// $user_list is now a mysqli resource

...

// line 59: code that expects $user_list to be a mysqli resource

Compare to:

$user_list = new user_list();
// $user_list is now an object

...

// line 59: code that expects $user_list to be a mysqli resource

You cannot return anything from a constructor. The new keyword will always give you an object, return values from the constructor go nowhere.

You also have an error in if ($group = ""), you mean if ($group == "").

deceze
You are right about the if statement. How else could I return the results if I can't use a traditional return?
DesignerGuy
@Desi If you'd go for proper OOP, the data would be stored inside the object, from where you'd use it. Returning a mysql resource from something that apparently attempts to approach ORM is kind of pointless. Either process the data in the class and return an array (not from the constructor though) or [implement the `Iterator` interface](http://php.net/manual/en/language.oop5.iterations.php) and use the object directly in loops. Right now it's kind of half-baked. :)
deceze