I wrote this class about a month ago as my first venture into the world of OOP. It's main purpose is to simplify/shorten the use of PDO. Any feedback is greatly appreciated. 🙂
<?php
class xs_connect
{
public $con;
public $error;
public function __construct($host=null, $db_name=null, $user=null, $password=null)
{
try
{
$db = new PDO('mysql:host='.$host.';dbname='.$db_name, $user, $password);
$this->con = $db;
}
catch(Exception $e)
{
$this->error = 1;
}
}
// Get multiple rows from the database.
public function getall($sql, $params=null)
{
if ($this->error != 1)
{
$stmt = $this->con->prepare($sql);
if ($params != null)
{
$param_number = 1;
foreach ($params as $id)
{
if ($id['type'] == 'str')
$stmt->bindparam($param_number, $id['value'], PDO::PARAM_STR);
elseif ($id['type'] == 'int')
$stmt->bindparam($param_number, $id['value'], PDO::PARAM_INT);
$param_number++;
}
}
$stmt->execute();
$result = $stmt->fetchall();
$stmt->closecursor();
return $result;
}
return false;
}
// Get one specific row.
public function getone($sql, $params=null)
{
if ($this->error != 1)
{
$stmt = $this->con->prepare($sql);
if ($params != null)
{
$param_number = 1;
foreach ($params as $id)
{
if ($id['type'] == 'str')
$stmt->bindparam($param_number, $id['value'], PDO::PARAM_STR);
elseif ($id['type'] == 'int')
$stmt->bindparam($param_number, $id['value'], PDO::PARAM_INT);
$param_number++;
}
}
$stmt->execute();
$result = $stmt->fetch();
$stmt->closecursor();
return $result;
}
return false;
}
// Preform an action (update, delete, truncate, create)
public function action($sql, $params=null)
{
if ($this->error != 1)
{
$stmt = $this->con->prepare($sql);
if ($params != null)
{
$param_number = 1;
foreach ($params as $id)
{
if ($id['type'] == 'str')
$stmt->bindparam($param_number, $id['value'], PDO::PARAM_STR);
elseif ($id['type'] == 'int')
$stmt->bindparam($param_number, $id['value'], PDO::PARAM_INT);
$param_number++;
}
}
$stmt->execute();
$stmt->closecursor();
return true;
}
return false;
}
}
?>
Used in this manor:
<?php
$db = new xs_connect('localhost', 'mydatabase', 'root', 'somepassword');
$sql = 'SELECT username
FROM users
WHERE user_id = ?;';
$params = array(
1 => array('type' => 'int', 'value' => $_POST['id'])
);
$username = $db->getone($sql, $params);
?>