Ok, so I have made something like this:
PHP Code:
class MyDb
{
private $dbh; # database connection
private $data; # array of values for prepared statement
private $stmt; # prepared statement
function __construct()
{
// Database settings
$host = 'localhost'; # won't need to change this 99% of the time
$user = 'root'; # database user
$pass = ''; # database password
$name = 'test'; # name of the database
// Connect to the database
try
{
$this->dbh = new PDO("mysql:host=$host;dbname=$name", $user, $pass, array(PDO::ATTR_PERSISTENT => true));
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); # set the error reporting attribute
}
catch (PDOException $e)
{
printf("<p>Error: %s</p>\n", $e->getMessage());
die();
}
}
// Remove object
function __destruct()
{
$this->dbh = NULL;
}
// Prepare a SELECT query
function prepareSelect($table, $data = NULL)
{
try
{
if (is_array($data))
{
$this->data = $data;
foreach ($data as $key => $val)
{
if (!isset($cond))
$cond = 'WHERE '.$key.' = :'.$key;
else
$cond .= ' AND '.$key.' = :'.$key;
}
$this->stmt = $this->dbh->prepare("SELECT * FROM $table $cond");
foreach ($data as $key => $val)
{
if (is_int($val))
$this->stmt->bindParam(':'.$key, $val, PDO::PARAM_INT);
else
$this->stmt->bindParam(':'.$key, $val, PDO::PARAM_STR);
}
}
else
{
$this->data = array();
$this->stmt = $this->dbh->prepare("SELECT * FROM $table");
}
}
catch (PDOException $e)
{
printf("<p>Error: %s</p>\n", $e->getMessage());
}
}
// Execute the prepared SELECT query
function executeSelect($data = NULL)
{
try
{
if (is_array($data))
$this->data = $data;
$this->stmt->execute($this->data);
return $this->stmt->fetchAll();
}
catch (PDOException $e)
{
printf("<p>Error: %s</p>\n", $e->getMessage());
}
}
}
Which can be used as:
PHP Code:
$conn = new MyDb();
$conn->prepareSelect('posts', array('id' => 1));
$result1 = $conn->executeSelect(); // Now the first execute will take the values from prepareSelect()
$result2 = $conn->executeSelect(array('id' => 2));
// etc
The problem is, I cannot change the number of variables on the run
Bookmarks