I reworked your example. Have a look at what I've made, investigate what you can through the manual, and go ahead and ask questions about everything you don't understand.
This is a quick example only, the code will likely be riddled with bugs and isn't the most flexible thing in the world, so don't bother copying it directly into use.
<?php
class Database {
private $host;
private $username;
private $database;
private $pdo;
private $connected = false;
public function __construct($username, $password, $database, $host = 'localhost')
{
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
}
public function connect()
{
$this->pdo = new PDO( "mysql:host={$this->host};dbname={$thos->database};charset=utf-8",
$this->username, $this->password );
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connected = true;
}
public function getDatabaseName()
{
return $this->database;
}
public function isConnected()
{
return $this->connected;
}
public function find($model, $limit = null, array $conditions = [])
{
$query = "SELECT * FROM `$model`";
if($conditions)
{
$values = [];
$conditionPairs = [];
foreach($conditions as $cond => $value)
{
$conditionPairs[] = "{$cond}?"
$values[] = $value;
}
$query .= " WHERE " . join(' AND ', $conditionPairs);
}
// $limit can be an array or a number, if it's an array, it's turned into
// LIMIT x,y
if($limit)
$query .= " LIMIT " . is_array($limit) ? join(", ", $limit) : $limit;
$handle = $pdo->prepare($query);
if(!$handle->execute($values ?: null))
{
// something failed, handle it
// this WILL throw an exception
}
// If we have a class available with the same name as
// the model, use it, otherwise, use a stdClass
if(class_exists($model, true))
{
$handle->setFetchMode(PDO::FETCH_CLASS, $model);
return $handle->fetchAll();
}
return $handle->fetchAll(PDO::FETCH_OBJ); // stdClass
}
}
// Note: ideally the constructor would only take a "database" argument
// and the "connect" method would take the "username", "host", and "password"
// arguments. This reinforces the idea that the same database may exist
// in different environments.
$db = new Database('username', 'password', 'database', 'host');
$db->connect();
// This is completely unecessary, just a demonstration:
if(!$db->isConnected())
throw new RuntimeException('boo');
// Select 10 products
$stickers = $db->query('stickers', 10);
foreach($stickers as $sticker)
{
echo $sticker->name;
echo $sticker->category;
}
// Select 1 product with id 5
$sticker = $db->query('stickers', 1, [ 'id=' => 5]);
echo $sticker->name;
echo $sticker->category;
// Select all products between 20 and 50 where "quantity" is above 6 and
// price is under or equal to 20
$stickers = $db->query('stickers', [20, 50], ['quantity>' => 6, 'price<=' => 20]);
// etc..