Advertisement
Guest User

Untitled

a guest
Sep 27th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.49 KB | None | 0 0
  1. <?php
  2. define('DEBUG', true);
  3. class Database{
  4.  
  5.     /**
  6.     * Connection Informations.
  7.     * @var string
  8.     */
  9.     private $host, $user, $pass, $db;
  10.    
  11.     /**
  12.     * The PDO layer.
  13.     * @var PDO
  14.     */
  15.     public $pdo;
  16.    
  17.     /**
  18.     * If the class is initiated, pdo included.
  19.     * @var bool
  20.     */
  21.     private $_init = false;
  22.    
  23.     /**
  24.     * Le numero de requêtes que cette classe a executer.
  25.     * @var int
  26.     */
  27.     private $queries = 0;
  28.    
  29.     public function __construct($host, $user, $db, $pass = '')
  30.     {
  31.         $this->host = $host;
  32.         $this->user = $user;
  33.         $this->db = $db;
  34.         $this->pass = $pass;
  35.         $this->construct_pdo();
  36.     }
  37.    
  38.     /**
  39.     * Construit PDO.
  40.     * @return void
  41.     */
  42.     private function construct_pdo(){
  43.         try{
  44.             $this->pdo = new PDO("mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this->pass);
  45.             $this->_init = true;
  46.         }
  47.         catch(PDOException $e){
  48.             exit("Erreur SQL: Impossible de se connecter au serveur.");
  49.             $this->_init = false;
  50.         }
  51.     }
  52.    
  53.     /**
  54.     * Execute une requête SELECT.
  55.     * @see Database::genSelect
  56.     * @return array
  57.     */
  58.     public function doSelect(array $fields, $from, array $conds = null){
  59.         $stmt = $this->pdo->prepare($this->genSelect($fields, $from, $conds));
  60.         if(!$stmt){
  61.             if(DEBUG)          
  62.                 exit('Erreur SQL !');
  63.             return false;
  64.         }
  65.         if(!$stmt->execute()){
  66.             if(DEBUG)          
  67.                 exit('Erreur SQL !');
  68.             return false;
  69.         }
  70.         ++$this->queries;
  71.         if($stmt->rowCount() == 1)
  72.         {
  73.             return $stmt->fetch(PDO::FETCH_ASSOC);
  74.         }
  75.         if($stmt->rowCount() > 1)
  76.         {
  77.             return $stmt->fetchAll(PDO::FETCH_ASSOC);
  78.         }
  79.         if($stmt->rowCount() < 1)
  80.         {
  81.             return array();
  82.         }
  83.     }
  84.    
  85.     /**
  86.     * Génère une requête SELECT.
  87.     * @param array $fields Les noms des colonnes à récuperer.
  88.     * @param string $from Le nom de la table.
  89.     * @param array $conds [optional] Les conditions
  90.     * @return string La requête généré.
  91.     */
  92.     private function genSelect(array $fields, $from, array $conds = null){
  93.         // Initiation de la requête
  94.         $query = 'SELECT ';
  95.         // Premièrement parsing des fields
  96.         $f = '';
  97.         foreach($fields as $key => $field)
  98.         {
  99.             $field = $from.'.'.$field;
  100.             if($key != (count($fields)-1))
  101.                 $field .= ',';
  102.             $field .= ' ';
  103.             // On ajoute
  104.             $f .= $field;
  105.         }
  106.         // On ajoute les fields à la requête
  107.         $query .= $f;
  108.         // puis la clause from
  109.         $query .= 'FROM '.$from;
  110.         if(isset($conds))
  111.         {
  112.             $query .= ' WHERE ';
  113.             $c = '';
  114.             foreach($conds as $field => $val)
  115.             {
  116.                 $cond = $from.".".$field." = '".$val."'";
  117.                 if(key($conds) != (count($conds)-1))
  118.                     $cond .= ' AND ';
  119.                 $c .= $cond;
  120.             }
  121.             $query .= $c;
  122.         }
  123.         return $query;
  124.     }
  125.    
  126.     /**
  127.     * Execute une requête INSERT.
  128.     * @see Database::genInsert
  129.     * @param array $values Les valeurs à être inséré.
  130.     * @return bool Résultat de l'opération.
  131.     */
  132.     public function doInsert(array $fields, $to, array $values){
  133.         // Si le nombre de valeurs fournies sont pas conformes :/
  134.         if(count($fields) !== count($values))
  135.             throw new Exception("Le nombre de valeurs n'est pas conforme aux nombres de colonnes.");
  136.         // On prépare la requête
  137.         $query = $this->genInsert($fields, $to);
  138.         $stmt = $this->pdo->prepare($query);
  139.         if(!$stmt){
  140.             if(DEBUG)          
  141.                 exit('Erreur SQL !');
  142.             return false;
  143.         }
  144.         $this->bindValues($stmt, $fields, $values);
  145.         $this->pdo->beginTransaction();    
  146.         if(!$stmt->execute())
  147.         {
  148.             $this->pdo->rollBack();
  149.             throw new Exception("Impossible d'éxecuter la requête: ".$query);
  150.         }
  151.         ++$this->queries;
  152.         return $this->pdo->commit();
  153.     }
  154.    
  155.     /**
  156.     * Génère une requête insert.
  157.     * @param array $fields Un tableau contenant les colonnes et leurs valeurs.
  158.     * @param string $to La table concerné.
  159.     * @return string
  160.     */
  161.     private function genInsert(array $fields, $to){
  162.         // Init the query
  163.         $query = 'INSERT INTO ';
  164.         // Now parse the fields and the params
  165.         $f = '';
  166.         $v = '';
  167.         foreach($fields as $k => $name)
  168.         {
  169.             $field = $name;
  170.             if($k != (count($fields)-1))
  171.                 $field .= ', ';
  172.             $f .= $field;
  173.             // Now values
  174.             $value = ":".$name;
  175.             if($k != (count($fields)-1))
  176.                 $value .= ', ';
  177.             $v .= $value;
  178.         }
  179.         $query .= $to.'('.$f.') ';
  180.         $query .= 'VALUES('.$v.')';
  181.         return $query;
  182.     }
  183.    
  184.     /**
  185.     * Ajoute les valeurs au statement.
  186.     * @see Database::doInsert
  187.     * @see Database::doUpdate
  188.     * @return void
  189.     */
  190.     private function bindValues(PDOStatement &$stmt, $fields, $vals){
  191.         foreach($fields as $k => $name)
  192.         {
  193.             $type = is_int($vals[$k]) ? PDO::PARAM_INT : PDO::PARAM_STR;
  194.             $stmt->bindValue($name, $vals[$k], $type);
  195.         }
  196.         return ;
  197.     }
  198. }
  199. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement