I am new to OOP in PHP and I am trying to understand how it work. I am trying to implement PDO into a my own class.
This is what I am doing:
class db {
private $options;
function __construct() {
$this->options = array(
'database_host' => DATABASE_HOST,
'database_name' => DATABASE_NAME,
'database_user' => DATABASE_USER,
'database_pass' => DATABASE_PASS
);
}
private function connect() {
try {
$pdo = new PDO('mysql:host=' . $this->options['database_host'] . ';dbname=' . $this->options['database_name'], $this->options['database_user'], $this->options['database_pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("set names utf8");
} catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
public function select($table, $what, $where, $custom) {
$query = "SELECT " . $what . " FROM " . $table;
$child = "1";
$param = array();
if ($where)
foreach ($where as $data => $value) {
if ($child == "1") {
$query .= " WHERE " . $data . " = '" . $value . "'";
$param[":" . $data] = $value;
$child = "next";
} else {
$query .= " AND " . $data . " = '" . $value . "'";
$param[":" . $data] = $value;
}
}
if ($custom)
$query .= ' ' . $custom;
$statement = $pdo->prepare($query);
if ($statement->execute($param))
return $statement->fetchAll(PDO::FETCH_ASSOC);
return false;
}
}
The problem is that I don't know how to make the function connect()
communicating with the below one select()
When I try to call the select()
function, I get this error:
Fatal error: Call to a member function prepare() on a non-object in /Applications/MAMP/htdocs/game/api/class.db.php on line 47
I would like that when I call the select()
function, the connect()
one connects to the DB and makes all its variables available for the other functions of the class...but I am lost.