Thursday, 30 August 2018

Php function does not return the class object

I have a DB class that I've created several functions in to return various values. One of the functions returns (or is supposed to) a "user" class object that represents a logged in user for the application.

class user {
   public $guid = '';
   public $fname = '';
   public $lname = '';

   public function __construct() {}

   public function print_option() {
         return "<option value='$this->guid'>$this->name</option>";
   }
}

In the DB class I have the following 2 functions:
public function get_user($uid) {
    $sql = '';
    $usr = new user();
    $sql = "SELECT guid, fname, lname FROM ms.users WHERE guid=?";

    if($sth = $this->conn->prepare($sql)) {
        $sth->bind_param('s', $uid);
        if($sth->execute()) {
            $sth->bind_result($usr->guid, $usr->fname, $usr->lname);
            $sth->fetch();
            print_r($usr);  // PRINTS OUT CORRECTLY
            return $usr;
        }
        else {return null;}
    }
    else {return null;}
}

public function get_practice_user_list($pguid) {
    $ret = '';
    $sql = "SELECT user_guid FROM ms.perm WHERE p_guid=?";
    if($sth = $this->conn->prepare($sql)) {
        $sth->bind_param('s', $pguid);
        if($sth->execute()) {
            $usr = new user();
            $guid = '';

            $sth->bind_result($guid);
            while($sth->fetch()) {
                print_r($guid);  // PRINTS GUID correctly
                $usr = $this->get_user($guid);
                print_r($usr);   // PRINTS NOTHING object is null so prints "error" two lines later.
                if($usr != null) $ret .= $usr->print_option();
                else print "error";
            }

            return $ret;
        }
        else {return null;}
    }
    else {return null;}
}

I'm just not understanding why the "user" object is not returning in this instance. Others calls to the get_user function work just fine and return the user class object pertaining to that user.
TIA

I guess you guid may be an integer so
    $sth->bind_param('s', $uid);

bind_param's first param should be 'i' not 's';

0 comments:

Post a Comment