Skip to content
Snippets Groups Projects
Commit 7b72b8ae authored by Cyril Vazquez's avatar Cyril Vazquez
Browse files

FEAT #2482 Class Database with PDO, used on ObjectCOntrollerAbstract

parent 27f7094b
No related branches found
No related tags found
No related merge requests found
...@@ -298,22 +298,22 @@ abstract class ObjectControler ...@@ -298,22 +298,22 @@ abstract class ObjectControler
require_once 'core/class/class_db_pdo.php'; require_once 'core/class/class_db_pdo.php';
$database = new Database(); $database = new Database();
$theQuery = "SELECT * FROM $table_name WHERE $table_id = :id " . $whereComp; $theQuery = "SELECT * FROM $table_name WHERE $table_id = :id " . $whereComp;
$database->query($theQuery); $queryParams = array(':id' => $id);
$database->bind(':id', $id);
if (count($params > 0)) { if (count($params > 0)) {
foreach ($params as $keyParam => $keyValue) { foreach ($params as $keyParam => $keyValue) {
$database->bind(":" . $keyParam, $keyValue); $queryParams[":" . $keyParam] = $keyValue;
} }
} }
$database->execute();
$stmt = $database->query($theQuery, $queryParams);
if ($database->rowCount() == 0) { if ($stmt->rowCount() == 0) {
return null; return null;
} else { } else {
// Constructing result // Constructing result
$object = new $object_name(); $object = new $object_name();
$rows = $database->resultset(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
for ($cpt=0;$cpt<count($rows);$cpt++) { for ($cpt=0;$cpt<count($rows);$cpt++) {
foreach ($rows[$cpt] as $key => $value) { foreach ($rows[$cpt] as $key => $value) {
......
<?php <?php
/*
class Database { * Copyright (C) 2015 Maarch
*
private $databasetype; * This file is part of Maarch.
*
* Maarch is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Maarch is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Maarch. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Class for database queries
*
* @package Core
*/
class Database
{
/**
* Prepared statements indexed by dsn and queryString
* @var array
*/
private static $preparedStmt = array();
private $driver;
private $server; private $server;
private $port; private $port;
private $user; private $user;
private $password; private $password;
private $database; private $database;
private $dsn;
private $dbh; private $pdo;
private $error; private $error;
private $stmt; private $stmt;
/**
* Constructor. Connects to the database if connection parameters are available in the session config
*/
public function __construct() public function __construct()
{ {
if (isset($_SESSION['config']['databaseserver'])) { if (isset($_SESSION['config']['databaseserver'])) {
$this->server = $_SESSION['config']['databaseserver']; $this->server = $_SESSION['config']['databaseserver'];
} }
if (isset($_SESSION['config']['databaseserverport'])) { if (isset($_SESSION['config']['databaseserverport'])) {
...@@ -32,112 +65,138 @@ class Database { ...@@ -32,112 +65,138 @@ class Database {
$this->database = $_SESSION['config']['databasename']; $this->database = $_SESSION['config']['databasename'];
} }
if (isset($_SESSION['config']['databasetype'])) { if (isset($_SESSION['config']['databasetype'])) {
$this->databasetype = $_SESSION['config']['databasetype']; switch($_SESSION['config']['databasetype']) {
if ($this->databasetype == 'POSTGRESQL') { case 'POSTGRESQL':
$this->databasetype = 'pgsql'; $this->driver = 'pgsql';
} elseif ($this->databasetype == 'MYSQL') { break;
$this->databasetype = 'mysql'; case 'MYSQL':
} elseif ($this->databasetype == 'ORACLE') { $this->driver = 'mysql';
$this->databasetype = 'oracle'; break;
case 'ORACLE':
$this->driver = 'oci';
break;
default:
print_r('DRIVER ERROR: Unknown database driver ' . $_SESSION['config']['databasetype']);
} }
} }
// Set DSN // Set DSN
$dsn = $this->databasetype $this->dsn = $this->databasetype
. ':host=' . $this->server . ':host=' . $this->server
. ';port=' . $this->port . ';port=' . $this->port
. ';dbname=' . $this->database; . ';dbname=' . $this->database
;
if (!isset(self::$preparedStmt[$this->dsn])) {
self::$preparedStmt[$this->dsn] = array();
}
// Set options // Set options
$options = array ( $options = array (
PDO::ATTR_PERSISTENT => true, PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_CASE => PDO::CASE_LOWER
); );
// Create a new PDO instanace // Create a new PDO instanace
try { try {
$this->dbh = new PDO($dsn, $this->user, $this->password, $options); $this->pdo = new PDO($this->dsn, $this->user, $this->password, $options);
} } catch (PDOException $PDOException) {
// Catch any errors $this->error = $PDOException->getMessage();
catch (PDOException $e) {
$this->error = $e->getMessage();
} }
if ($this->error && $_SESSION['config']['debug'] == 'true') { if ($this->error && $_SESSION['config']['debug'] == 'true') {
print_r('SQL ERROR:' . $this->error); print_r('SQL ERROR:' . $this->error);
} }
} }
public function query($query) /**
* Begin a new transaction
*
* @return bool
*/
public function beginTransaction()
{ {
$this->stmt = $this->dbh->prepare($query); return $this->pdo->beginTransaction();
} }
public function bind($param, $value, $type = null) /**
* Commit a transaction
*
* @return bool
*/
public function commit()
{ {
if (is_null($type)) { return $this->pdo->commit();
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
} }
public function execute() /**
* Rollback a transaction
*
* @return bool
*/
public function rollback()
{ {
return $this->stmt->execute(); return $this->pdo->rollback();
} }
public function resultset() /**
* Check if in a transaction
*
* @return bool
*/
public function inTransaction()
{ {
$this->execute(); return $this->pdo->inTransaction();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
} }
public function single() /**
* Prepare a query and returns the statement.
* Save the prepared statement for a later execution with parameters
* @param string $queryString The SQL query string to prepare
*
* @return PDOStatement
*/
public function prepare($queryString)
{ {
$this->execute(); if (!isset(self::$preparedStmt[$this->dsn][$queryString])) {
return $this->stmt->fetch(PDO::FETCH_ASSOC); self::$preparedStmt[$this->dsn][$queryString] = $this->pdo->prepare($queryString);
} }
public function rowCount() return self::$preparedStmt[$this->dsn][$queryString];
{
return $this->stmt->rowCount();
} }
public function lastInsertId() /**
* Prepare and execute a query. Returns the prepared and executed statement.
* Statement can be used to fetch resulting rows OR by a later call to a fetch method
* @param string $queryString The SQL query string
* @param array $parameters An indexed or associative array of parameters
* @param bool $catchExceptions Indicates wheter the PDO exceptions must be caught
*
* @return PDOStatement The prepared and executed statement
*
* @throws PDOException If a PDO error occurs during preparation or execution
*/
public function query($queryString, $parameters=null, $catchExceptions=false)
{ {
return $this->dbh->lastInsertId(); try {
} $this->stmt = $this->prepare($queryString);
public function beginTransaction() $executed = $this->stmt->execute($parameters);
{ } catch (PDOException $PDOException) {
return $this->dbh->beginTransaction(); if ($catchExceptions) {
} $this->error = $PDOException->getMessage();
public function endTransaction() return false;
{ } else {
return $this->dbh->commit(); throw $PDOException;
} }
}
public function cancelTransaction() return $this->stmt;
{
return $this->dbh->rollBack();
} }
public function debugDumpParams()
{
return $this->stmt->debugDumpParams();
}
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment