PDO :: FETCH_ASSOC不返回值。 我对不同方法感到困惑,你能帮我解决一下吗?

I am quite unused with php. I want to create a menu by taking objects from a database, but i am confused by all the different methods of doing so (both from school and internet) and i need to make some order in my mind.

This is what i have done until now, i use two different classes for doing so.

Db.php

class Db extends PDO {

    private $uname;
    private $passwd;
    private $hostname;
    private $dbname;

    public function __construct() {
        $this->uname = "root";
        $this->passwd = "";
        $this->hostname = "127.0.0.1";
        $this->dbname = "myclienti";

        try {
            parent::__construct('mysql:charset=utf8mb4;host=' . $this->hostname . ';dbname=' . $this->dbname, $this->uname, $this->passwd);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

}

Servizie.php

class Servizie {
    private $codice_utente;
    private $desc_servizio;
    private $puntopresa;



    function getCodice_utente() {
        return $this->codice_utente;
    }

    function getDesc_servizio() {
        return $this->desc_servizio;
    }

    function getPuntopresa() {
        return $this->puntopresa;
    }

    function setCodice_utente($codice_utente) {
        $this->codice_utente = $codice_utente;
    }

    function setDesc_servizio($desc_servizio) {
        $this->desc_servizio = $desc_servizio;
    }

    function setPuntopresa($puntopresa) {
        $this->puntopresa = $puntopresa;
    }




    public function getAllServizie() {
        $db = new Db();

        $query = 'select CODICE_UTENTE, DESC_SERVIZIO, PUNTOPRESA from serviziele';
        $statement = $db->prepare($query);
        $statement->execute();
        $object = $statement->fetchAll(PDO::FETCH_ASSOC);
        return $object;

    }

}

Part of my index page where i want to put my menu.

       <?php
        $servizie = new Servizie();


        $list = $servizie->getAllServizie();
        echo '<div id="dropdown-contentelectr">';
        foreach ($list as $element){
            echo '<a href="#">' . $element->PUNTOPRESA . '</a>';
        }

        echo '</div>';
        ?>

Sorry for my english.

When fetching as Associative Array, you retrive data by index

$element['PUNTOPRESA'];

If you want to fetch as Class/instance, use:

PDO::FETCH_INTO
PDO::FETCH_CLASS

Or for \stdClass which returns an anonymous object.

PDO::FETCH_OBJ

These will allow to access properties of the fetched object with arrow notation.

Usage:

statement->fetchAll(PDO::FETCH_OBJ);

For more, read: http://php.net/manual/en/pdostatement.fetch.php

If you want an example of Database class look at that (it's part of a micro-framework so just take it as example, written by me): https://github.com/yuxblank/phackp/blob/master/src/phackp/core/Database.php