0

I'm struggling to get something I think should be really simple to work. I have created a class which connects to a database using PDO and would like to initially just create a function to pass direct SQL queries to it.

class PDO_MySQL
{
    private $_db;
    private $connection_string;

    public function __construct()
    {
        $this->_db = new PDO($this->connection_string, DB_USERNAME, DB_PASSWORD);
    }
    public function DB_Query($sql)
    {
        $query = $this->_db->query($sql);
        return $query;
    }
}

Then in my code:

$db = new PDO_MySQL();
$people = $db->DB_Query("SELECT * FROM about_us");
print_r($people);

But this is returning

PDOStatement Object ( [queryString] => SELECT * FROM about_us )

When I am looking for it to return a results set.

The connection string is set and the connection is fine i've just removed excess code for this post.

Secondary question, is this the best approach? I'm moving from MySQLi and non-Class based scripts.

MattP
  • 2,798
  • 2
  • 31
  • 42
  • 1
    [Here](http://tr.php.net/manual/en/pdostatement.fetchall.php) everything is explained more than great. – Leri May 30 '12 at 11:43
  • or see this tutorial: http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html .. i think what you are missing here is fetchAll – Arfeen May 30 '12 at 11:46
  • Thanks, fetchAll has got it working. Is there an equivalent to mysqli fetch_object() without using the PDO FETCH_INTO or FETCH_CLASS? – MattP May 30 '12 at 11:50
  • @PLB the documentation shows this line can be added to return as an object $query->setFetchMode(PDO::FETCH_OBJ); before the fetch() or fetchAll() – MattP May 30 '12 at 11:59
  • @MattP Yes, you can do so, but I don't use. – Leri May 30 '12 at 12:02
  • Also check out this question. It's a bit different but may be helpful: http://stackoverflow.com/questions/2047264/use-of-pdo-in-classes – Buttle Butkus May 21 '13 at 19:14

1 Answers1

1

Instead of

public function DB_Query($sql)
{
    $query = $this->_db->query($sql);
    return $query;
}

you have to do:

public function DB_Query($sql)
{
    $query = $this->_db->prepare($sql);
    $query->execute();
    return $query->fetchAll();
}

because

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object

Leri
  • 12,367
  • 7
  • 43
  • 60