*/
class DB {
private $conn = NULL;
private $error = NULL;
/**
* Connects to SQL Server
*
* @return true/false
*/
public function connect($driver, $host, $user, $pass, $db, $port = Null) {
if (!extension_loaded("pdo")) die("Missing PDO PHP extension."); // check if extension loaded
try {
switch (strtolower($driver)) {
case "mysql":
if (!extension_loaded("pdo_mysql")) die("Missing pdo_mysql PHP extension."); // check if extension loaded
if(empty($port)) $port=3306;
$this->conn = new PDO("mysql:host=".$host.";port=".$port.";dbname=".$db, $user, $pass);
break;
case "pgsql":
if (!extension_loaded("pdo_pgsql")) die("Missing pdo_pgsql PHP extension."); // check if extension loaded
if(empty($port)) $port=5432;
$this->conn = new PDO("pgsql:host=".$host.";port=".$port.";dbname=".$db, $user, $pass);
break;
case "sqlite":
if (!extension_loaded("pdo_sqlite")) die("Missing pdo_sqlite PHP extension."); // check if extension loaded
if(!file_exists($db)) {
@touch($db);
}
if(file_exists($db) && is_readable($db) && is_writable($db)) {
$this->conn = new PDO("sqlite:".$db, $user, $pass);
} else {
$this->error = "cant crate/connect the/to sqlite database";
return false;
}
break;
default:
$this->error = "not supported database type found";
return false;
break;
}
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/*
* close the database connection
*/
public function close () {
$this->conn = NULL;
}
/**
* Sends a database query to SQL server.
*
* @param string $res a database query
* @param array $bind
* @return integer id of the query result
*/
public function query ($res, $bind = array()) {
try {
$query = Null;
$query = $this->conn->prepare($res);
if(is_array($bind) && !empty($bind))
$query->execute($bind);
else
$query->execute();
return $query;
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
/**
* Gets a row from SQL database query result.
*
* @param string $res a database query
* @return array a row from result
*/
public function fetch_array ($res) {
try {
return $res->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
/**
* return the last insert id
*/
public function last_id () {
return $this->conn->lastInsertId();
}
/**
* Returns SQL error number for last error.
*
* @return integer MySQL error number
*/
public function error () {
return $this->error;
}
}
?>