Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Bd_Conexao
- {
- //para alterar estes valores vá ao arquivo configDB
- private static $instancia = NULL; //se der prob mudar p private
- private $server = SERVER;
- private $user = USER;
- private $password =PASSWORD ;
- public static $conexao; //retirar static
- public static $status ="Zerada!"; //retirar static
- protected function __construct()
- {
- if(self::$conexao==NULL){
- self::$conexao = mysqli_connect($this->server, $this->user, $this->password) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- self::$status = "Iniciada!";
- }
- }
- function __toString() {
- return self::$status;
- }
- //singleton da conexao
- public function getConexao()
- { //self::getInstancia();
- if((self::$conexao==null) ||(self::$conexao==false)){
- //self::$conexao = mysqli_connect($this->server, $this->user, $this->password) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- echo "Conexao inexistente!![] <br>";
- }else{echo "Conexao ok!![ ] <br>";}
- //$this->ver();
- return self::$conexao;
- }
- //singleton da classe my_deprecated
- public static function getInstancia()
- {
- if(self::$instancia==NULL) {
- self::$instancia = new self;
- echo "Nova instancia!![] <br>";
- }else{
- echo "instancia ja existente!![] <br>";
- }
- //self::ver();
- return self::$instancia;
- }
- public function query($sql)
- {
- self::$status = "Requerida Query!";
- //echo var_dump(self::$conexao);
- //return self::$conexao->query($sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- //mysqli_set_charset(self::$conexao,'utf8');
- $result = mysqli_query(self::$conexao,$sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- return $result;
- }
- public function prepare($sql)
- {
- $result = mysqli_prepare(self::$conexao,$sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- return $result;
- }
- public function multiquery($sql)
- {
- mysqli_set_charset($this->getConexao(),'utf8');
- $r = mysqli_multi_query( $this->getConexao(),$sql) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- return $r;
- }
- public function select_db($db)
- { //$this->getConexao();
- self::$status = "Requerira BD!";
- $r = mysqli_select_db(self::$conexao, $db) or die("erro: ".mysqli_error(self::$conexao)." num: ".mysqli_errno(self::$conexao));
- return $r;
- }
- public function __destruct()
- {
- if(self::$conexao){mysqli_close(self::$conexao) or die("Houve um erro ao fechar a conexão"); }
- self::$conexao = "Finalizada!";
- return $r;
- }
- }
- <?php
- class My_ORM
- {
- private $bd; //objeto contendo instancia de mysqli
- private $base; //nome da base de dados
- private $tabela; //nome da tabela
- private $primaryKey = 'id'; //nome da chave primaria
- //variaveis usadas pelos metodos da fluent interface
- private $comand;
- private $from;
- private $where;
- private $order;
- private $group;
- private $limit;
- private $params;
- private $lastQuery;
- function __construct($tabela,$base="",$primarykey="")
- {
- //$this->bd = Mysql::getInstance();
- $this->bd = Bd_Conexao::getInstancia();
- $this->tabela = $tabela;
- $this->base = $base;
- if($primarykey){ $this->primaryKey= $primarykey; }
- return $this;
- }
- public function _setBase($base)
- {
- $this->bd = Bd_Conexao::select_db($base);
- return $this;
- }
- public function select($campos="")
- {
- $this->comand = "SELECT ";
- $this->campos = ($campos!="") ? $campos : "*";
- return $this;
- }
- //funcoes da fi
- public function where($where="")
- {
- $this->where = $where;
- return $this;
- }
- //adaptaão para uso de prepared statements
- public function bind()
- {
- $num = func_num_args();
- if($num>0){
- for($i=0; $i<$num;$i++){
- $this->params[]= func_get_arg($i);
- }
- }
- return $this;
- }
- public function from($tabela="")
- {
- $this->from = ($tabela) ? $tabela : $this->tabela;
- return $this;
- }
- public function limit($limit="")
- {
- $this->limit = $limit;
- return $this;
- }
- public function order($order="")
- {
- $this->order = $order;
- return $this;
- }
- public function group($group="")
- {
- $this->group = $group;
- return $this;
- }
- public function getFrom()
- {
- return $this->from;
- }
- //string com a query montada
- public function getQuery()
- {
- // $sql = $this->comand.$this->campos;
- $sql = $this->comand.$this->campos;
- $sql .= ($this->from) ? " FROM " .$this->from: "";
- $sql .= ($this->where) ? " WHERE ".$this->where : "";
- $sql .= ($this->order) ? " ORDER BY ".$this->order : "";
- $sql .= ($this->group) ? " GROUP BY ".$this->group : "";
- $sql .= ($this->limit) ? " LIMIT ".$this->limit : "";
- $sql .= ";";
- $this->lastQuery = $sql;
- return $sql;
- }
- public function find($type='')
- {
- $this->bd->select_db($this->base);
- $smtp = $this->bd->query($this->getQuery()) or die("erro: ".mysqli_error(Bd_Conexao::$conexao)." num: ".mysqli_errno(Bd_Conexao::$conexao));
- return $smtp;
- }
- public function findArray($firs="")
- {
- $smtp = $this->find();
- if($smtp){
- while($result = mysqli_fetch_assoc($smtp)) {
- $resultado[] = $result;
- }
- }
- return ($firs==1 && $resultado) ? $resultado[0] : $resultado;
- }
- public function findObj($firs="")
- {
- $smtp = $this->find();
- if($smtp){
- while($result = mysqli_fetch_object($smtp)) {
- $resultado[] = $result;
- }
- }
- return ($firs==1 && $resultado) ? $resultado[0] : $resultado;
- }
- /* @$obj (array) | (object stdclass)
- */
- function insert($obj)
- {
- $obj = array_filter((array)$obj); //retira campos com valores nulos
- if(!$this->tabela){
- throw new Exception("USER Exception: Nome da tabela não informado!");
- }else if( isset($obj[$this->primaryKey]) ){
- throw new Exception("USER Exception: Objeto a inserir não pode ter a primary key preenchida.");
- }
- $campos = array_keys($obj);
- $valores = $this->_toBank(array_values($obj));
- //comando SQL que insere os dados no banco de dados
- $sql = "INSERT INTO " . $this->tabela . " ( " ;
- $sql.= implode(',',$campos);
- $sql.= ") VALUES ( ";
- $sql.= implode(',', $valores);
- $sql.= "); ";
- $this->lastQuery = $sql;
- $result = $this->bd->query($sql);
- if($result){
- $resultado = mysqli_insert_id($this->bd->getConexao());
- }
- return $resultado;
- }
- public function update($obj,$condicao ,$campos="")
- {
- $obj = (array)$obj;
- $dados = array_values($obj);
- if(!$this->tabela){
- throw new Exception("User Exception: Nome da tabela não informado!");
- }
- if(!$campos){
- $campos = array_keys($obj);
- }else if(is_string($campos)){
- $campos = explode(',',$campos);
- }
- if(!in_array($this->primaryKey, $campos) && !$condicao){
- throw new Exception("User Exception: Primary key ou condição não informados!");
- }
- //comando SQL que altera os dados no banco de dados
- $sql = "UPDATE " . $this->tabela . " SET " . "`".$campos[0]."` = \"".$dados[0]."\"";
- for($i = 1; $i<count ( $campos ) ; $i++ )
- {
- $sql.= ", `".$campos[$i]."`= \"".$dados[$i]."\"";
- }
- if($condicao){
- echo $sql.= " WHERE " . $condicao;
- }
- $this->lastQuery = $sql;
- $resultado = $this->bd->query($sql);
- return $resultado;
- }
- public function delete($condicao,$param="")
- {
- if(!$this->tabela){
- throw new Exception("User Exception: Nome da tabela não informado!");
- }else if(!$condicao){
- throw new Exception("User Exception: Informe a condição!");
- }
- //comando SQL que altera os dados no banco de dados
- $sql = "DELETE FROM " . $this->tabela ;
- $sql.= " WHERE " . $condicao;
- $this->lastQuery = $sql;
- $resultado = $this->bd->query($sql);
- //$resultado = $sel->execute($params);
- return $resultado;
- }
- private function getDados($campos,$dados)
- {
- if(is_string($campos)){
- $campos = explode(',',$campos);
- }
- if(is_array($campos)){
- foreach($campos as $c){
- $obj[] = $dados[$c];
- }
- return $obj;
- }
- }
- //acrescenta aspas dulas nas strings dos campos
- private function _toBank($array){
- foreach($array as $k=>$v){
- $array[$k] = "\"".$v."\"";
- }
- return $array;
- }
- function __toString()
- {
- return $this->lastQuery;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement