Search code examples
phpmysqlibindprepare

Binding to class properties and fetching to array - php mysqli bind_result


Im trying something like this:

class kategoria
{
    public $IdKat;
    public $IdKatNad;
    public $NazwaKat;
}

function get_cats()  
{  

    $query = "SELECT IdKat, NazwaKat, OpisKat  FROM `kategorie`"; 

    try
    {
        $stmt = $this->link->prepare($query);

        /* bind parameters for markers */
        //$stmt->bind_param("i", $idKat);

        $stmt->execute();
        $kat = new kategoria();

        $stmt->bind_result(
                $kat->Idkat, 
                $kat->NazwaKat, 
                $kat->OpisKat
                );


        $output = array();

        while ($stmt->fetch()) {
            $output += array(clone $kat);
        }

        $stmt->close();
    }
    catch (Exception $e)
    {
        echo $e;
    }

    echo '<pre>';
    print_r($output);
    echo '</pre>';
}

At the end - i have only last row in array. Why? When i tried with array (and 2 fields), without "kategoria" class - it worked, but i need to put query result in array of objects representing table rows. what im doing wrong? Im new in PHP.


Solution

  • I had to serialize and deserialize my class binded to result set.

    $output += array(deserialize(serialize($kat)));