Advertisement
Guest User

Untitled

a guest
Jun 5th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.94 KB | None | 0 0
  1. <?php
  2. class Bd_Conexao
  3. {  
  4.     //para alterar estes valores vá ao arquivo configDB
  5.    private static $instancia = NULL; //se der prob mudar p private
  6.    private $server = SERVER;
  7.    private $user = USER;
  8.    private $password =PASSWORD ;
  9.    public static $conexao; //retirar static
  10.    public static $status ="Zerada!"; //retirar static
  11.  
  12.    protected function __construct()
  13.    {
  14.  
  15.  
  16.         if(self::$conexao==NULL){
  17.  
  18.            self::$conexao = mysqli_connect($this->server, $this->user, $this->password) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  19.            self::$status = "Iniciada!";
  20.        }
  21.          
  22.    }
  23.  
  24.    function  __toString() {
  25.        return self::$status;
  26.    }
  27.    //singleton da conexao
  28.    
  29.    public function getConexao()
  30.    {   //self::getInstancia();
  31.        if((self::$conexao==null) ||(self::$conexao==false)){
  32.            
  33.         //self::$conexao = mysqli_connect($this->server, $this->user, $this->password) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  34.         echo "Conexao inexistente!![] <br>";
  35.        
  36.        }else{echo "Conexao ok!![ ] <br>";}
  37.        //$this->ver();
  38.       return self::$conexao;
  39.    }
  40.  
  41.    //singleton da classe my_deprecated
  42.    public static function getInstancia()
  43.    {
  44.        if(self::$instancia==NULL)       {
  45.          self::$instancia = new self;
  46.          
  47.          echo "Nova instancia!![] <br>";
  48.        }else{
  49.            echo "instancia ja existente!![] <br>";
  50.        }
  51.        //self::ver();
  52.        return self::$instancia;
  53.    }
  54.  
  55.    public function query($sql)
  56.    {  
  57.        self::$status = "Requerida Query!";
  58.        //echo var_dump(self::$conexao);
  59.        //return self::$conexao->query($sql)  or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  60.        //mysqli_set_charset(self::$conexao,'utf8');
  61.        $result = mysqli_query(self::$conexao,$sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  62.        return $result;
  63.     }
  64.  
  65.    public function prepare($sql)
  66.    {    
  67.        $result = mysqli_prepare(self::$conexao,$sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  68.        return $result;
  69.    }
  70.  
  71.    public function multiquery($sql)
  72.    {
  73.        mysqli_set_charset($this->getConexao(),'utf8');
  74.        $r = mysqli_multi_query( $this->getConexao(),$sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  75.        return $r;
  76.     }
  77.  
  78.    public function select_db($db)
  79.    {   //$this->getConexao();
  80.        self::$status = "Requerira BD!";
  81.        $r = mysqli_select_db(self::$conexao, $db) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
  82.        return  $r;
  83.     }
  84.  
  85.     public function __destruct()
  86.    {  
  87.        if(self::$conexao){mysqli_close(self::$conexao) or die("Houve um erro ao fechar a conexão"); }
  88.        self::$conexao = "Finalizada!";
  89.        return $r;
  90.    }
  91. }
  92. <?php
  93. class My_ORM
  94. {
  95.     private $bd; //objeto contendo instancia de mysqli
  96.     private $base; //nome da base de dados
  97.     private $tabela; //nome da tabela
  98.     private $primaryKey = 'id'; //nome da chave primaria
  99.    
  100.     //variaveis usadas pelos metodos da fluent interface
  101.     private $comand;
  102.     private $from;
  103.     private $where;
  104.     private $order;
  105.     private $group;
  106.     private $limit;
  107.     private $params;
  108.     private $lastQuery;
  109.    
  110.     function  __construct($tabela,$base="",$primarykey="")
  111.     {
  112.        //$this->bd = Mysql::getInstance();
  113.        $this->bd = Bd_Conexao::getInstancia();
  114.        $this->tabela = $tabela;
  115.        $this->base = $base;
  116.        if($primarykey){ $this->primaryKey= $primarykey; }
  117.        return $this;
  118.     }
  119.  
  120.     public function _setBase($base)
  121.     {
  122.  
  123.        $this->bd = Bd_Conexao::select_db($base);
  124.        return $this;
  125.     }
  126.  
  127.     public function select($campos="")
  128.     {
  129.         $this->comand = "SELECT ";
  130.         $this->campos = ($campos!="") ? $campos : "*";
  131.         return $this;
  132.     }
  133.     //funcoes da fi
  134.     public function where($where="")
  135.     {
  136.         $this->where = $where;
  137.         return $this;
  138.     }
  139.  
  140.     //adaptaão para uso de prepared statements
  141.     public function bind()
  142.     {
  143.         $num = func_num_args();
  144.         if($num>0){
  145.             for($i=0; $i<$num;$i++){
  146.                 $this->params[]= func_get_arg($i);
  147.             }
  148.         }
  149.         return $this;
  150.     }
  151.  
  152.     public function from($tabela="")
  153.     {
  154.         $this->from = ($tabela) ? $tabela : $this->tabela;
  155.         return $this;
  156.     }
  157.  
  158.     public function limit($limit="")
  159.     {
  160.      $this->limit = $limit;
  161.      return $this;
  162.     }
  163.  
  164.     public function order($order="")
  165.     {
  166.         $this->order = $order;
  167.         return $this;
  168.     }
  169.  
  170.     public function group($group="")
  171.     {
  172.         $this->group = $group;
  173.         return $this;
  174.     }
  175.  
  176.     public function getFrom()
  177.     {
  178.         return $this->from;
  179.     }
  180.     //string com a query montada
  181.     public function getQuery()
  182.     {
  183.            // $sql = $this->comand.$this->campos;
  184.             $sql = $this->comand.$this->campos;
  185.             $sql .= ($this->from) ? " FROM " .$this->from: "";
  186.             $sql .= ($this->where) ? " WHERE ".$this->where : "";
  187.             $sql .= ($this->order) ? " ORDER BY ".$this->order : "";
  188.             $sql .= ($this->group) ? " GROUP BY ".$this->group : "";
  189.             $sql .= ($this->limit) ? " LIMIT ".$this->limit : "";
  190.             $sql .= ";";
  191.             $this->lastQuery = $sql;
  192.             return $sql;
  193.     }
  194.  
  195.     public function find($type='')
  196.     {  
  197.         $this->bd->select_db($this->base);
  198.            
  199.  
  200.             $smtp = $this->bd->query($this->getQuery()) or die("erro: ".mysqli_error(Bd_Conexao::$conexao)." num: ".mysqli_errno(Bd_Conexao::$conexao));
  201.  
  202.         return $smtp;
  203.     }
  204.  
  205.     public function findArray($firs="")
  206.     {
  207.         $smtp = $this->find();
  208.         if($smtp){
  209.            while($result = mysqli_fetch_assoc($smtp)) {
  210.                   $resultado[] = $result;
  211.            }
  212.         }
  213.         return ($firs==1 && $resultado) ? $resultado[0] : $resultado;
  214.     }
  215.  
  216.     public function findObj($firs="")
  217.     {
  218.         $smtp = $this->find();
  219.         if($smtp){
  220.            while($result = mysqli_fetch_object($smtp)) {
  221.                   $resultado[] = $result;
  222.            }
  223.         }
  224.         return ($firs==1 && $resultado) ? $resultado[0] : $resultado;
  225.     }
  226.  
  227.  
  228.     /* @$obj (array) | (object stdclass)
  229.      */
  230.     function insert($obj)
  231.     {
  232.                 $obj =  array_filter((array)$obj); //retira campos com valores nulos
  233.                
  234.                 if(!$this->tabela){
  235.                     throw new Exception("USER Exception: Nome da tabela não informado!");
  236.                 }else if( isset($obj[$this->primaryKey]) ){
  237.                     throw new Exception("USER Exception: Objeto a inserir não pode ter a primary key preenchida.");
  238.                 }
  239.                
  240.                 $campos =  array_keys($obj);
  241.                 $valores =  $this->_toBank(array_values($obj));
  242.                
  243.         //comando SQL que insere os dados no banco de dados
  244.         $sql = "INSERT INTO " . $this->tabela . " ( " ;
  245.                 $sql.= implode(',',$campos);
  246.  
  247.                 $sql.= ")  VALUES ( ";
  248.                 $sql.= implode(',', $valores);                
  249.                 $sql.= "); ";
  250.  
  251.                 $this->lastQuery = $sql;
  252.                 $result = $this->bd->query($sql);
  253.              
  254.                 if($result){
  255.                     $resultado = mysqli_insert_id($this->bd->getConexao());
  256.                  }
  257.         return $resultado;
  258.     }
  259.    
  260.     public function update($obj,$condicao ,$campos="")
  261.     {
  262.      
  263.         $obj = (array)$obj;
  264.         $dados =  array_values($obj);
  265.  
  266.         if(!$this->tabela){
  267.             throw new Exception("User Exception: Nome da tabela não informado!");
  268.         }
  269.         if(!$campos){
  270.             $campos =  array_keys($obj);
  271.         }else if(is_string($campos)){
  272.             $campos =  explode(',',$campos);
  273.         }
  274.        
  275.         if(!in_array($this->primaryKey, $campos) && !$condicao){
  276.             throw new Exception("User Exception: Primary key ou condição não informados!");
  277.         }
  278.         //comando SQL que altera os dados no banco de dados
  279.         $sql = "UPDATE " . $this->tabela . " SET " . "`".$campos[0]."` = \"".$dados[0]."\"";
  280.  
  281.         for($i = 1; $i<count ( $campos ) ; $i++ )
  282.         {
  283.             $sql.= ", `".$campos[$i]."`= \"".$dados[$i]."\"";
  284.         }
  285.  
  286.         if($condicao){
  287.             echo     $sql.= "  WHERE " . $condicao;
  288.         }
  289.  
  290.         $this->lastQuery = $sql;
  291.        
  292.         $resultado = $this->bd->query($sql);
  293.         return $resultado;
  294.     }
  295.  
  296.     public function delete($condicao,$param="")
  297.     {  
  298.         if(!$this->tabela){
  299.             throw new Exception("User Exception: Nome da tabela não informado!");
  300.         }else if(!$condicao){
  301.             throw new Exception("User Exception: Informe a condição!");
  302.         }
  303.      
  304.         //comando SQL que altera os dados no banco de dados
  305.         $sql = "DELETE FROM "  . $this->tabela ;
  306.         $sql.= "  WHERE " . $condicao;
  307.  
  308.         $this->lastQuery = $sql;
  309.        
  310.         $resultado = $this->bd->query($sql);
  311.         //$resultado = $sel->execute($params);
  312.  
  313.         return $resultado;
  314.     }
  315.  
  316.     private function getDados($campos,$dados)
  317.     {
  318.        if(is_string($campos)){
  319.            $campos = explode(',',$campos);
  320.        }
  321.  
  322.        if(is_array($campos)){
  323.             foreach($campos as $c){            
  324.                 $obj[] =  $dados[$c];
  325.             }
  326.             return $obj;
  327.        }
  328.     }
  329.  
  330.     //acrescenta aspas dulas nas strings dos campos
  331.     private function _toBank($array){
  332.         foreach($array as $k=>$v){
  333.             $array[$k] = "\"".$v."\"";
  334.         }
  335.         return $array;
  336.     }
  337.     function  __toString()
  338.     {
  339.         return $this->lastQuery;
  340.     }
  341. }
  342. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement