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.

6
  • 1
    Here everything is explained more than great. Commented May 30, 2012 at 11:43
  • or see this tutorial: phpro.org/tutorials/Introduction-to-PHP-PDO.html .. i think what you are missing here is fetchAll Commented May 30, 2012 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? Commented May 30, 2012 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() Commented May 30, 2012 at 11:59
  • @MattP Yes, you can do so, but I don't use. Commented May 30, 2012 at 12:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.