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.
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
as a last argument to thenew PDO()
constructor for better debugging. – Fineganconnect_PDO
function (or something like it). – FineganSQLSTATE[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.";dbname=".$database
on the end of the PDO dsn statement. – Vanbuskirk