How To Execute PDO Queries Inside a Class With PHP and MYSQL

Executing PHP Queries Within a Class With PHP / MYSQL

I will keep this example short and sweet. The whole idea here is to pass the database connection into a PHP class. Within the class, the queries will execute and the results are returned as a usable string.

The Class

  class MyClass
{
    public $number;
    public $PDO;

    public function __construct($PDO)
    {
        $this->number($PDO);
    }

    public function number($PDO)
    {
        $command = "SELECT number FROM tablename WHERE id > 0 LIMIT 1 ";
        $result = $PDO->prepare($command);
        $result->execute();

        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $this->number = $row['number'];
        }
    }

    public function __toString()
    {
        return $this->number;
    }
}