Simple PDO Wrapper not working
Asked Answered
V

1

1

I'm trying out this Wrapper and no matter what I always just get 'boolean false' when I var_dump($row) in my index.php file.

Here is my db class:

<?php
// database.php
class DB {
protected $_connection = array();  // to map the connection
protected $_dbh;                   // property which keeps the database handler
protected $_database;              // property to keep the database name
protected $_table;                 // property to keep the table name
protected $_query;                 // property to keep a query statement

public function __construct() {

    // require the database configurations as an array from config.php
    $this->_connection = require_once 'config.php';
    // define which database driver to use (mysql?) and extract the values as 
    // variables
    extract($this->_connection['connection']['mysql']);

    // make the database and table name available to the class
    $this->_database = $database;
    $this->_table    = $table_name;

    // Check for PDO driver and create the connection to the database.
    try {
        $this->_dbh = new PDO($driver.":host=".$host, $username, $password);
    } catch (PDOException $e) {
        die ('Connection failed: ' . $e->getMessage());
    }
}

public function input_query($query) {
    $this->_query = $this->_dbh->prepare($query);
    return $this;
}

public function execute() {
    return $this->_query->execute();
}

public function single() {
    $this->execute();
    return $this->_query->fetch();
}

public function result_set() {
    $this->execute();
    return $this->fetchAll();
}    
}

And then in my index.php file:

<?php
// index.php
require_once 'database.php';

$db = new DB();

$db->input_query("SELECT `name` FROM `names` WHERE `id`=1");
$r = $db->single();

var_dump($r);

And if I do

<?php
// index.php 
require_once 'database.php';

$db = new DB();
var_dump($db);

I get an object:

object(DB)[1]
  public '_connection' => 
    array (size=1)
      'connection' => 
        array (size=4)
          'sqlite' => 
            array (size=3)
              ...
          'mysql' => 
            array (size=6)
              ...
          'pgsql' => 
            array (size=6)
              ...
          'sqlsrv' => 
            array (size=6)
              ...
  protected '_dbh' => 
    object(PDO)[2]
  protected '_database' => string 'pagination_demo' (length=15)
  protected '_table' => string 'names' (length=5)
  protected '_query' => null

But var_dump($r) always returns boolean false and sometimes when I try different things with the code I get 'Call to an undefined method DB::single()', or 'method on a non-object' kind of message.

Can anyone help me sort this out?

Many thanks. Regards.

Vanbuskirk answered 14/8, 2012 at 13:59 Comment(18)
You do not appear to have selected a database, so it's probably your query that is in error. Add array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) as a last argument to the new PDO() constructor for better debugging.Finegan
For the sake of my sanity if nothing else, please can people stop writing wrapper classes for PDO. It does not need an OO wrapper, it is already OO. If you want additional functionality/sugar methods, extend it.Strong
Try to wrap execute with try/catch and check the errorCode;Folksy
I suggest using this connect_PDO function (or something like it).Finegan
@Folksy I tried wrapping try/catch around $r = db->execute() and it returned: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected. Like @Francis Avila thought. What do I do? ...p.s. I also changed the class so that it extends PDO. Makes sense, thanks @DaveRandom.Vanbuskirk
@Strong I changed to class so that it extends PDO. Makes sense. Thanks!Vanbuskirk
Ok, sometimes I feel stupid. I forgot to put the .";dbname=".$database on the end of the PDO dsn statement.Vanbuskirk
@Strong Tell me about it. It makes me want to create one of those Pimp My Ride pics that says "Yo dawg, I heard you like wrappers, so I put a wrapper around your wrapper..."Atlantes
@kevinmajor1 "With just one more layer of abstraction I can take over the world!"Strong
@kevinmajor1, take it easy guys. I'm learning this stuff. No need to be rude. There's a difference between suggesting a better solution giving that one is a more experienced programmer than the one who'w asking questions instead of being insulting. If you hate helping newbies don't help them.Vanbuskirk
@DaveRandom, and goes for you to.Vanbuskirk
@VilliMagg It's not really a personal attack on you and neither are we intending to be rude/unhelpful, although I see how it comes across that way; it's the summation of seeing people - many of them experienced programmers - do the same silly things over and over. You have just thrown yours into the ring at the wrong time, that's all. And your reaction to it was definitely among the better ones - I have also had people outright refuse to listen. You should read the link I posted in my last comment though, it's well worth it - or there's a video of the actual talk floating around somewhere.Strong
@VilliMagg Looking at your code below though, I'm not sure why you are doing this, you don't really appear to have added functionality, only complexity - can you explain what the end goal is? Or is it just an educational exercise?Strong
@VilliMagg Yeah, it's nothing personal. It's just that PDO and MySQLi are already wrappers around a db instance. Wrapping them doesn't make a lot of sense in most cases.Atlantes
@DaveRandom. Alright guys. Thanks for opening my eyes to the matter. It was helpful, but I, like so many others, just don't know any better since there's so much bad info out there on the web. Thanks for directing me into the right direction. It's difficult to find real quality info and books that are more than 2 years old are already obsolete.Vanbuskirk
@Strong The reason for me doing this demo is for educational purposes and to gain more fundamental knowledge and exercise in more advanced concepts of oop in php. I feel that my "beginner/intermediate" level knowledge is limiting me and it frustrates me. Plus it's not just for educational purposes, I intend to expand on this. This is just the beginning to get it to work. I have much more to add now that I've gotten it to work, thanks to you and the others. Thank you.Vanbuskirk
@KevinM1 pbs.twimg.com/media/A9621KLCcAAfqv-.jpgZenobiazeolite
@jasondavis Briliant! :)Atlantes
V
0

Ok, now it works perfectly. And here is the code:

<?php // database.php
class DB extends PDO {

    protected $_connection = array();         // to map the connection

    protected $_dbh;                        // property which keeps the database handler

    protected $_database;                   // property to keep the database name

    protected $_table;                      // property to keep the table name

    protected $_query;                       // property to keep a query statement

    public function __construct() {

        // require the database configurations as an array from config.php
        $this->_connection = require_once 'config.php';
        // define which database driver to use (mysql?) and extract the values as variables
        extract($this->_connection['connection']['mysql']);

        // make the database and table name available to the class
        $this->_database = $database;
        $this->_table    = $table_name;

        // build the dsn string value for the PDO connection
        $dsn = $driver.":host=".$host.";dbname=".$database;

        // Check for PDO driver and create the connection to the database.
        try {
            parent::__construct($dsn, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        } catch (PDOException $e) {
            die ('Connection failed: ' . $e->getMessage());
        }
    }

    public function input_query($query) {
        $this->_query = parent::prepare($query);
        return $this;
    }

    public function execute() {
        return $this->_query->execute();
    }

    public function single() {
        $this->execute();
        return $this->_query->fetch();
    }

    public function result_set() {
        $this->execute();
        return $this->_query->fetchAll();
    }
}

And the index.php file:

<?php
require_once 'database.php';

$db = new DB();

$db->input_query("SELECT `name` FROM `names`");

try {
    $r = $db->result_set();
} catch (PDOException $e) {
    die ($e->getMessage());
}
var_dump($r);

And var_dump($r) gave me a whole bunch of names.

Thank you guys so much for your help!

Vanbuskirk answered 14/8, 2012 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.