Rui Pinheiro Rui Pinheiro - 4 months ago 11
PHP Question

How to pass arrays in OOP PHP?

I want to pass an array from the class Database to the class Characters, someone can help me?

My Code:

Class Database

class Database {

public function DBCharactersMerchandise() {

$db = $this->connection();

$uid = $_SESSION['id'];

$this->conn = $db->prepare("SELECT * FROM mercadoria WHERE cid = :mid");
$this->conn->execute(array(':mid' => $uid));

while($row = $this->conn->fetch(PDO::FETCH_ASSOC)){

$array = [

$row['type'], // here I have 'apple' and 'orange'

];

return $array;

}

}
}


Class Characters

Class Characters {

public function getUserMerchandise() {

$db = new Database();
$type = $db->DBCharactersMerchandise();

foreach ($type as $value) {

echo $value; // I want echo 'apple' and 'orange' here

}

}
}


I think you can understand what I want, so I someone could help me I appreciate.

Answer

You need to load the array in the while loop, and then return it after the while loop is completed

class Database {

    public function DBCharactersMerchandise() {

        $db = $this->connection();    
        $uid = $_SESSION['id'];

        $this->conn = $db->prepare("SELECT * FROM `mercadoria` WHERE `cid` = :mid");
        $this->conn->execute(array(':mid' => $uid));

        $array = [];

        while($row = $this->conn->fetch(PDO::FETCH_ASSOC)){
            $array[] = $row['type'];
        }
        return $array;    
    }   
}

Or better still select just what you want to use, this will speed up the query, then you can use ->fetchAll to load a complete result array ready to return

class Database {

    public function DBCharactersMerchandise() {

        $db = $this->connection();    
        $uid = $_SESSION['id'];

        $this->conn = $db->prepare("SELECT `type` FROM `mercadoria` WHERE `cid` = :mid");
        $this->conn->execute(array(':mid' => $uid));

        $array = $this->conn->fetchAll(PDO::FETCH_ASSOC)){

        return $array;    
    }   
}