Ollicca Mindstorm
Ollicca Mindstorm

Reputation: 608

Return multiple results from class with return instead echo?

I am new to PHP OOP.

I want to retreive all results from the db, but not using echo inside the method but RETURN (as I hear often methods shouldn't echo anything but only return), as I am doing in the following:

class MySqlDb {

    public $conn;
    public $numRows;

    function __construct($host, $un, $p, $db) {
        $this->conn = new mysqli($host, $un, $p, $db);
    }

    function get_smth() {
        // $conn = new mysqli($host, $un, $p, $db);
        $q = "SELECT * FROM posts";
        $r = $this->conn->query($q) or die(mysqli_error());
        $this->numRows = $r->num_rows;
        // return "<p>A total of $this->numRows records were found</p>";
        while ($row = $r->fetch_assoc()) {
            echo $row['title'].'<br>';
        }
    }

}

$t = new MySqlDb( 'localhost', 'root', '', 'oop' );
$t->get_smth();

I would like to change echo $row['title'].'<br>'; to return $row['title'].'<br>'; and still work the same (now I just get the first result if I use return). What needs changing?

Upvotes: 0

Views: 87

Answers (3)

Maximus2012
Maximus2012

Reputation: 1819

function get_smth() {
    // $conn = new mysqli($host, $un, $p, $db);
    $q = "SELECT * FROM posts";
    $r = $this->conn->query($q) or die(mysqli_error());
    return  $r->fetch_all();
}

then iterate through the result when calling the function:

foreach ($t->get_smth() as $array){
    // do something
}

Upvotes: 0

IanPudney
IanPudney

Reputation: 6021

In PHP (and most languages), execution of a function stops once it reaches the first return statement. In order to return multiple things, you have to return some sort of data structure - the most common is an array.

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

Just load everything into an array and return the array. Keep the output formatting out of this class and leave that up to the whatever is calling this class.

$return_array = array();
while ($row = $r->fetch_assoc()) {
    $return_array[]['title'] =  $row['title'];
}
return $return_array;

Upvotes: 0

Related Questions