Advertisement
ricardogodoi

BancoDeDados.php

Jan 7th, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.88 KB | None | 0 0
  1. /*
  2. CONFIGURAÇÃO DO SISTEMA ( CAMILLE )
  3. INOVE WS
  4. (BANCO DE DADOS)
  5.  
  6. @programador Paulo Ricardo Santos Godoi. (http://facebook.com/ricardo.sis)
  7. @versao 0.1a
  8.  
  9. Sistema baseado no script (https://github.com/matyre73)
  10. @author: Wade Dunbar
  11. @version: 1.0
  12.  
  13. */
  14.  
  15. // Precisa dessa Função para gerar logs de erros no script abaixo.
  16. require("Logs.php");
  17.  
  18. class db_conectar{
  19.  
  20. // Gera logs de erros.
  21. //private $log;
  22.  
  23. // Definindo Variáveis de banco de dados
  24. //private $servidor, $usuario, $senha, $banco, $conexao, $charSet;
  25. private $hostname, $username, $password, $database, $dbDriver, $charSet;
  26.  
  27. // Variáveis de Ligação
  28. private $BancoDeDados, $query_num, $insert_id;
  29.  
  30. function __construct($settings){
  31.  
  32. isset($settings['hostname']) ? $this->hostname = $settings['hostname']: die ("Servidor não encontrado!");
  33. isset($settings['username']) ? $this->username = $settings['username']: die ("Login não encontrado!");
  34. isset($settings['password']) ? $this->password = $settings['password']: die ("Senha incorreta!");
  35. isset($settings['database']) ? $this->database = $settings['database']: die ("Banco de Dados não encontrado!");
  36.  
  37. $this->dbDriver = isset($settings['dbDriver']) ? $settings['dbDriver']: "mysql";
  38. $this->charSet = isset($settings['charSet']) ? $settings['charSet']: "utf8";
  39.  
  40. // Conecta-se ao Banco de Dados.
  41. $this->log = new Log();
  42. $this->connect();
  43. }
  44.  
  45.  
  46.  
  47.  
  48. // Função que conecta-se no banco de dados
  49. // É necessário ter definido as seguintes constantes: DB_NAME, DB_HOST, DB_USER, DB_PASSWORD
  50. private function connect(){
  51. try{
  52. $this->db_conectar = new PDO("$this->dbDriver:host=$this->hostname;dbname=$this->database;$this->charSet", $this->username, $this->password);
  53. $this->error_handling();
  54. } catch (PDOException $error) {
  55. // Date para registro nos logs
  56. $date = date("d/m : H:i : ");
  57.  
  58. //Criar log's de erro de conexão
  59. file_put_contents('../includes/logs/db.conexao.error.txt', $date.$error->getMessage().PHP_EOL,FILE_APPEND);
  60.  
  61. echo 'Atenção! Ocorreu um erro ao tentar se conectar ao banco de dados. <br/> Caso o erro persistir contate o administrador do sistema! <br/> ', $e->getMessage();
  62. // Deixar Página em branco ao exibir os erros.
  63. die($error);
  64. }
  65. return $this->db_conectar;
  66. }
  67. /*private function connect(){
  68. try{
  69. $this->db_conectar = new PDO("$this->dbDriver:host=$this->hostname;dbname=$this->database;$this->charSet", $this->username, $this->password);
  70. $this->error_handling();
  71. }catch(PDOException $error){
  72. die($error);
  73. }
  74. }
  75. */
  76.  
  77. private function error_handling(){
  78. if($this->db_conectar){
  79. $this->db_conectar->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  80. $this->db_conectar->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  81. }
  82. }
  83.  
  84. private function _print($var){
  85. echo is_array($var) ? "<pre>".print_r($var,true)."</pre>": $var."<br>";
  86. }
  87.  
  88.  
  89.  
  90.  
  91.  
  92. // Função que faz a consulta da tabela no banco de dados.
  93. /*
  94.  
  95. // Insert
  96. $consulta = $BancoDeDados->query("SELECT * FROM Table");
  97. */
  98. function query($query, $show = null){
  99. ($show) ? $this->_print($query): "";
  100. if($consulta = $this->db_conectar->query($query)):
  101. return $consulta;
  102. else:
  103. $this->_print($this->db_conectar->errorInfo());
  104. endif;
  105. }
  106.  
  107.  
  108.  
  109.  
  110.  
  111. // Função que faz a consulta da tabela,coluna no banco de dados.
  112. /*
  113.  
  114. // Insert
  115. $consulta = $BancoDeDados->query_prepare("SELECT * FROM someTable WHERE something = :comparison", array(':comparison' => $comparison));
  116. $data = $BancoDeDados->fetch_array($consulta);
  117. */
  118. function query_prepare($query, $prepare, $show = false){
  119. if($show){
  120. $this->_print($query);
  121. $this->_print($prepare);
  122. }
  123.  
  124. $consulta = $this->db_conectar->prepare($query);
  125. if($consulta->execute($prepare)){
  126. return $consulta;
  127. }else{
  128. $this->_print($this->db_conectar->errorInfo());
  129. }
  130. }
  131.  
  132. function num_rows_affected(&$consulta){
  133. return (isset($consulta))? $consulta->rowCount(): "";
  134. }
  135.  
  136. function fetch_array(&$consulta){
  137. $fetchType = PDO::FETCH_ASSOC;
  138. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  139. }
  140.  
  141. function fetch_array_assoc(&$consulta){
  142. $fetchType = PDO::FETCH_ASSOC;
  143. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  144. }
  145.  
  146. function fetch_both(&$consulta){
  147. $fetchType = PDO::FETCH_BOTH;
  148. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  149. }
  150.  
  151. function fetch_bound(&$consulta){
  152. $fetchType = PDO::FETCH_BOUND;
  153. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  154. }
  155.  
  156. function fetch_class(&$consulta){
  157. $fetchType = PDO::FETCH_CLASS;
  158. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  159. }
  160.  
  161. function fetch_num(&$consulta){
  162. $fetchType = PDO::FETCH_NUM;
  163. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  164. }
  165.  
  166. function fetch_object(&$consulta){
  167. $fetchType = PDO::FETCH_OBJ;
  168. return (isset($consulta)) ? $consulta->fetchAll($fetchType): "";
  169. }
  170.  
  171. function num_rows($consulta){
  172. return (isset($consulta)) ? $consulta->rowCount(): "";
  173. }
  174.  
  175.  
  176.  
  177.  
  178.  
  179. // Função que cadastra algo no banco de dados.
  180. /*
  181.  
  182. // Insert
  183. $insert = $BancoDeDados->insert("nome_tabela", array("nome_coluna"=>"valor_da_coluna"));
  184.  
  185. // Do something with the data
  186. if($insert > 0 ) {
  187. return 'Parabens! Dados inseridos com sucesso!';
  188. }
  189.  
  190. */
  191. function insert($table, $arFieldValues, $show = FALSE){
  192. $escVals = array();$excVals = array();$cnt = 0;
  193.  
  194. $fields = array_keys($arFieldValues);
  195. $values = array_values($arFieldValues);
  196.  
  197. foreach($values as $val){
  198. $key = ":$cnt";
  199. $escVals[] = $key;
  200. $excVals[$key] = $val;
  201. $cnt++;
  202. }
  203.  
  204. $sql = " INSERT INTO $table (" . join(', ',$fields) . ") VALUES(" . join(', ',$escVals) . ")";
  205.  
  206. ($show) ? $this->_print($sql): "";
  207.  
  208. $consulta = $this->db_conectar->prepare($sql);
  209. $res = $consulta->execute($excVals);
  210. $this->insert_id = $this->db_conectar->lastInsertId();
  211. return $res;
  212. }
  213.  
  214.  
  215.  
  216.  
  217.  
  218. // Função que atualiza dados no banco de dados
  219. /*
  220.  
  221. // Update
  222. $update = $BancoDeDados->update('nome_tabela',array('thisfield' => value, 'field2'=>value2),array('conditionfield'=>conValue));
  223.  
  224. */
  225. function update($table, $arFieldValues, $arConditions, $show = FALSE){
  226. $arUpdates = array();$excVals = array();$arWhere = array();$cnt = 0;
  227. foreach($arFieldValues as $field => $val){
  228. $key = ":$cnt";
  229. $arUpdates[] = "$field = $key";
  230. $excVals[$key] = $val;
  231. $cnt++;
  232. }
  233.  
  234. foreach($arConditions as $field => $val){
  235. $key = ":$cnt";
  236. $arWhere[] = "$field = $key";
  237. $excVals[$key] = $val;
  238. $cnt++;
  239. }
  240.  
  241. $sql = "UPDATE $table SET ". join(', ',$arUpdates) . " WHERE " . join(' AND ',$arWhere);
  242.  
  243. if($show){
  244. $this->_print($sql);
  245. $this->_print($excVals);
  246. }
  247.  
  248. $consulta = $this->db_conectar->prepare($sql);
  249. $res = $consulta->execute($excVals);
  250. return $res;
  251. }
  252.  
  253.  
  254.  
  255.  
  256.  
  257. // Função que deleta algo do banco de dados
  258. /*
  259.  
  260. // Delete
  261. $delete = $BancoDeDados->delete("nome_tabela", array("nome_coluna"=>"valor_da_coluna"));
  262.  
  263. */
  264. function delete($table, $arConditions, $show = FALSE){
  265. $arWhere = array();$excVals = array();$cnt = 0;
  266.  
  267. foreach($arConditions as $field => $val){
  268. $key = ":$cnt";
  269. $arWhere[] = "$field = $key";
  270. $excVals[$key] = $val;
  271. $cnt++;
  272.  
  273. }
  274.  
  275. $sql = "DELETE FROM $table WHERE " . join(' AND ',$arWhere);
  276.  
  277. ($show) ? $this->_print($sql): "";
  278.  
  279. $consulta = $this->db_conectar->prepare($sql);
  280. foreach($excVals as $k => $v){
  281. $consulta->bindParam("$k", $v);
  282. }
  283. $res = $consulta->execute();
  284. return $res;
  285. }
  286.  
  287.  
  288.  
  289.  
  290.  
  291. function last_insert_id($var = FALSE){
  292. $id = ($var) ? $this->db_conectar->lastInsertId(): ($this->db_conectar) ? $this->insert_id: 0;
  293. return $id;
  294. }
  295.  
  296. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement