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.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
Villi Magg
  • 1,163
  • 3
  • 13
  • 23
  • 1
    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. – Francis Avila Aug 14 '12 at 14:06
  • 13
    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. – DaveRandom Aug 14 '12 at 14:07
  • 1
    Try to wrap execute with try/catch and check the errorCode; – pomaxa Aug 14 '12 at 14:08
  • I suggest using [this `connect_PDO` function](http://stackoverflow.com/a/10455228/1002469) (or something like it). – Francis Avila Aug 14 '12 at 14:09
  • @pomaxa 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. – Villi Magg Aug 14 '12 at 14:58
  • @DaveRandom I changed to class so that it extends PDO. Makes sense. Thanks! – Villi Magg Aug 14 '12 at 14:59
  • Ok, sometimes I feel stupid. I forgot to put the `.";dbname=".$database` on the end of the PDO dsn statement. – Villi Magg Aug 14 '12 at 15:06
  • @DaveRandom 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..." – Major Productions Aug 14 '12 at 15:48
  • 2
    @kevinmajor1 ["With just one more layer of abstraction I can take over the world!"](https://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka-humanity-epic-fail.aspx) – DaveRandom Aug 14 '12 at 15:54
  • 1
    @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. – Villi Magg Aug 14 '12 at 18:36
  • 1
    @DaveRandom, and goes for you to. – Villi Magg Aug 14 '12 at 18:37
  • @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. – DaveRandom Aug 14 '12 at 18:47
  • 1
    @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? – DaveRandom Aug 14 '12 at 18:48
  • @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. – Major Productions Aug 14 '12 at 19:20
  • @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. – Villi Magg Aug 14 '12 at 21:37
  • @DaveRandom 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. – Villi Magg Aug 14 '12 at 21:44
  • 1
    @KevinM1 https://pbs.twimg.com/media/A9621KLCcAAfqv-.jpg – JasonDavis Dec 12 '12 at 13:59
  • @jasondavis Briliant! :) – Major Productions Dec 12 '12 at 14:10

1 Answers1

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!

Villi Magg
  • 1,163
  • 3
  • 13
  • 23