awl1991 awl1991 - 2 months ago 6
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



<?php
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){
try{

$db = new PDO(self::$socket.':'.'host'.'='.self::$host.';'
.'dbname'.'='.self::$db_name,self::$username,self::$password);

$this -> instance = $db;

} catch(PDOException $e){

die($e -> getMessage());

}
}

}

//Queries
public function query($sql){

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

return $query;

}

}


PDO Object






<?php
require_once('db.php');

$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

Answer

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;

}

https://secure.php.net/manual/en/pdostatement.fetch.php

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

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