Alex
Alex

Reputation: 2072

PHP - unable to instantiate objects with data

I'm studying PHP and building a simple web app to save\get data from the database. I built a User class and I'm trying to create objects based upon that class and pass the relevant parameters to the constructor. I am able to retrieve data from the db, followed several guides and I still receive an empty array in the front.

class User{
    protected $firstName;
    protected $lastName;
    protected $pass;

    function __construct($firstn,$lastn,$upass){
        $this->firstName = $firstn;
        $this->lastName = $lastn;
        $this->pass = $upass;
    }
   function setFname($first){
       $this->firstName = $first;
   }
   function setLname($last){
       $this->lastName = $last;
   }
   function setPass($pass){
       $this->pass = $pass;
   }

}

This is the part where I'm creating user objects and push them into the array.

    if($stmt =mysqli_prepare($conn, $getUsersStatement)){
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt,$first,$last,$pass,$id);
        $resultArray = [];
        while(mysqli_stmt_fetch($stmt)){
//            $user = new User($first,$last,$pass);
            $user = new User($first,$last,$pass);
            $user->setFname($first);
            $user->setLname($last);
            $user->setPass($pass);
//                $user->lastName =$last;
//                $user->pass =$pass;
//            printf ("%s %s %s\n", $first, $last, $pass,$id); //this works and prints the data
            array_push($resultArray,$user);
        }
        /* close statement */
        echo (json_encode($resultArray));
        mysqli_stmt_close($stmt);
    }

This is the output:

[{},{},{},{},{},{},{}]

Upvotes: 0

Views: 42

Answers (2)

iainn
iainn

Reputation: 17434

json_encode won't display any protected properties of your class. If you're using PHP 5.4+, you can add the following method to your class:

public function jsonSerialize()
{
    return get_object_vars($this);
}

and change the definition to

class User implements JsonSerializable {

This will make all fields available to the encoder.

(Alternatively as a quicker fix, set your fields to public instead, but that's not as clean.)

Upvotes: 3

niklas
niklas

Reputation: 3011

Is that your full code? You need to bind the fetched rows to variables like so:

mysqli_stmt_bind_result($stmt, $first, $last, $pass);

see http://php.net/manual/de/mysqli-stmt.fetch.php

If you do:

$user = new User('MyFirstname','MyLastname','MyNotSecurePassword');
array_push($resultArray, $user);

it should work. Check if your $first,$last,$pass variables are set!

Upvotes: 0

Related Questions