awl1991 awl1991 - 8 months ago 31
MySQL Question

Where am I going wrong with my PDO class?

I am a little new to the PDO object, and I am simply trying to make a connection to the database and return a mySQL query. I have scoured the internet (including this site) to try and find the solution. I have found many similar solutions, but nothing is working. I know that it is probably a really simple fix, but I can't seem to find it.

Thanks in advance for your help!

PDO Class

class Database {

private static $host = "localhost";
private static $db_name = "c9";
private static $username = "theandrewilliam";
private static $password = "";
private static $socket = "mysql";

//Instance of class
private $instance = NULL;

//Connection to Database (predefined function)
public function __construct(){

if($this -> instance == NULL){

$db = new PDO(self::$socket.':'.'host'.'='.self::$host.';'

$this -> instance = $db;

} catch(PDOException $e){

die($e -> getMessage());



public function query($sql){

$query = $this -> instance = prepare($sql);
$query -> execute();

return $query;



PDO Object


$data = new Database();

$sq = 'SELECT * FROM body';

$result = $data -> query($sq);

while($row = $result -> $query -> fetch(PDO::FETCH_ASSOC)){

$body = $row['text'];
echo $body;


Error thrown

Fatal error: Call to undefined function prepare() in
/home/ubuntu/workspace/db.php on line 36 Call Stack: 0.0003 233728 1.
{main}() /home/ubuntu/workspace/post.php:0 0.0011 254688 2.
Database->query() /home/ubuntu/workspace/post.php:8


The method fetch() is used by a PDOStatement (here, $result). So you should remove $query in your while.

while($row = $result -> fetch(PDO::FETCH_ASSOC)){

    $body = $row['id'];
    echo $body;


Edit: You have some typo when using the prepare method, it should be:

$query = $this -> instance -> prepare($sql);