We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

MartinY on 10/10/07


Tagged

mysql class php


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

heinz1959
Nix


DB_mysql


Published in: PHP 


Clase para base de datos MySQL

  1. /** DEBUG - BASE DE DATOS **/
  2. define("DEBUG_DB", true);
  3.  
  4. /** inicio: clase DB_mysql **/
  5. class DB_mysql {
  6.  
  7. /* variables de conexión */
  8. var $BaseDatos;
  9. var $Servidor;
  10. var $Usuario;
  11. var $Clave;
  12.  
  13. /* identificador de conexión y consulta */
  14. var $Conexion_ID = 0;
  15. var $Consulta_ID = 0;
  16.  
  17. /* número de error y texto error */
  18. var $Errno = 0;
  19. var $Error = '';
  20.  
  21. /* ultimo string sql consultado */
  22. var $ultimo_sql = '';
  23.  
  24. /** contructor: DB_mysql() **/
  25. function DB_mysql($bd = "", $host = "", $user = "", $pass = "") {
  26. $this->BaseDatos = $bd;
  27. $this->Servidor = $host;
  28. $this->Usuario = $user;
  29. $this->Clave = $pass;
  30.  
  31. $this->conectar($bd, $host, $user, $pass);
  32. }
  33.  
  34. /*Conexión a la base de datos*/
  35. function conectar($bd, $host, $user, $pass) {
  36. if (!empty($bd)) $this->BaseDatos = $bd;
  37. if (!empty($host)) $this->Servidor = $host;
  38. if (!empty($user)) $this->Usuario = $user;
  39. if (!empty($pass)) $this->Clave = $pass;
  40.  
  41. // Conectamos al servidor
  42. $this->Conexion_ID = mysql_connect($this->Servidor, $this->Usuario, $this->Clave) or die(mysql_error());
  43. if (!$this->Conexion_ID) {
  44. $this->Error = 'Ha fallado la conexión. Error: '.mysql_error();
  45. return 0;
  46. }
  47.  
  48. //seleccionamos la base de datos
  49. if (!mysql_select_db($this->BaseDatos, $this->Conexion_ID)) {
  50. $this->Error = 'Imposible abrir '.$this->BaseDatos.'. Error: '.mysql_error();
  51. return 0;
  52. }
  53.  
  54. /* Si hemos tenido éxito conectando devuelve
  55. el identificador de la conexión, si no devuelve 0 */
  56. return $this->Conexion_ID;
  57. }
  58.  
  59. /* Cierra la conexión */
  60. function cerrar() {
  61. mysql_close($this->Conexion_ID);
  62. }
  63.  
  64. /* Ejecuta un consulta */
  65. function consulta($sql='', $debug=false) {
  66. if (empty($sql)) {
  67. $this->Error = 'No ha especificado una consulta SQL';
  68. return 0;
  69. }
  70. // si esta activado el debug y queremos mostrar el SQL
  71. if (DEBUG_DB && $debug) echo $sql;
  72. // guardamos el string sql como el ultimo utilizado
  73. $this->ultimo_sql = $sql;
  74. //ejecutamos la consulta
  75. $this->Consulta_ID = mysql_query($sql, $this->Conexion_ID);
  76. if (!$this->Consulta_ID) {
  77. $this->Errno = mysql_errno();
  78. $this->Error = mysql_error();
  79. } else {
  80. $this->Errno = 0;
  81. $this->Error = '';
  82. }
  83. /* Si hemos tenido éxito en la consulta devuelve
  84. el identificador de la consulta, si no devuelve 0 */
  85. return $this->Consulta_ID;
  86. }
  87.  
  88. /* Devuelve el número de campos de una consulta */
  89. function numcampos() {
  90. return mysql_num_fields($this->Consulta_ID);
  91. }
  92.  
  93. /* Devuelve el número de registros de una consulta */
  94. function numregistros() {
  95. return mysql_num_rows($this->Consulta_ID);
  96. }
  97.  
  98. /* Devuelve el nombre de un campo de una consulta */
  99. function nombrecampo($numcampo) {
  100. return mysql_field_name($this->Consulta_ID, $numcampo);
  101. }
  102.  
  103. function execute($sql) {
  104. // guardamos el string sql como el ultimo utilizado
  105. $this->ultimo_sql = $sql;
  106. $result = mysql_query($sql, $this->Conexion_ID);
  107. if (empty($result)) {
  108. $this->Errno = mysql_errno();
  109. $this->Error = mysql_error();
  110. } else {
  111. $this->Errno = 0;
  112. $this->Error = '';
  113. }
  114. return $result;
  115. }
  116.  
  117. /* Comienza una transacción */
  118. function beginTrans() {
  119. $this->execute('SET AUTOCOMMIT=0');
  120. $this->execute('START TRANSACTION');
  121. return true;
  122. }
  123.  
  124. /* Commit */
  125. function commitTrans() {
  126. $this->execute('COMMIT');
  127. $this->execute('SET AUTOCOMMIT=1');
  128. return true;
  129. }
  130.  
  131. /* Rollback */
  132. function rollbackTrans() {
  133. $this->execute('ROLLBACK');
  134. $this->execute('SET AUTOCOMMIT=1');
  135. return true;
  136. }
  137.  
  138. function agregar($tabla, $datos_values, $debug=false) {
  139. $sql_keys = '';
  140. $sql_values = '';
  141. foreach($datos_values as $key => $value) {
  142. $sql_keys .= $key.", ";
  143. if (strcasecmp($value,'NULL') === 0) $sql_values .= "NULL, ";
  144. else $sql_values .= "'".$value."', ";
  145. }
  146. $sql_keys = substr($sql_keys, 0, -2);
  147. $sql_values = substr($sql_values, 0, -2);
  148. $sql = "INSERT INTO `".$tabla."` (".$sql_keys.") VALUES (".$sql_values.")";
  149. $this->execute($sql);
  150. if (DEBUG_DB && $debug) echo $sql;
  151. if (!empty($this->Error)) {
  152. if ($this->Errno == 1062) {
  153. echo '<br/>Error al insertar en '.$tabla.': [dato duplicado]';
  154. $this->printLastErrorNumber();
  155. $this->printLastError();
  156. $this->printLastSQL();
  157. $this->rollbackTrans();
  158. //return 1;
  159. } else {
  160. echo '<br/>Error al insertar en '.$tabla.':';
  161. $this->printLastErrorNumber();
  162. $this->printLastError();
  163. $this->printLastSQL();
  164. $this->rollbackTrans();
  165. }
  166. }
  167. return 0;
  168. }
  169.  
  170. function actualizar($tabla, $datos_set, $datos_where, $debug=false) {
  171. $sql = "UPDATE `".$tabla."` SET ";
  172. foreach ($datos_set as $key => $value) {
  173. if (strcasecmp($value,'NULL') === 0)
  174. $sql .= "`".$key."`=NULL, ";
  175. else
  176. $sql .= "`".$key."`='".$value."', ";
  177. }
  178. $sql = substr($sql, 0, -2);
  179. $sql .= " WHERE ";
  180. foreach ($datos_where as $key => $value) {
  181. $sql .= $key."='".$value."' AND ";
  182. }
  183. $sql = substr($sql, 0, -5);
  184. $this->execute($sql);
  185. if (DEBUG_DB && $debug) echo $sql;
  186. if (!empty($this->Error)) {
  187. echo '<br/>Error al actualizar '.$tabla.':';
  188. $this->printLastErrorNumber();
  189. $this->printLastError();
  190. $this->printLastSQL();
  191. $this->rollbackTrans();
  192. }
  193. return 0;
  194. }
  195.  
  196. function borrar($tabla, $datos_where, $debug=false) {
  197. $sql = "DELETE FROM `".$tabla."` WHERE ";
  198. foreach ($datos_where as $key => $value) {
  199. $sql .= "`".$key."`='".$value."' AND ";
  200. }
  201. $sql = substr($sql, 0, -5);
  202. $this->execute($sql);
  203. if (DEBUG_DB && $debug) echo $sql;
  204. if (!empty($this->Error)) {
  205. echo '<br/>Error al borrar '.$tabla.':';
  206. $this->printLastErrorNumber();
  207. $this->printLastError();
  208. $this->printLastSQL();
  209. $this->rollbackTrans();
  210. }
  211. return 0;
  212. }
  213.  
  214. function existe($tabla, $datos_where, $debug=false) {
  215. $sql = "SELECT COUNT(*) AS DATO FROM `".$tabla."` WHERE ";
  216. foreach ($datos_where as $key => $value) {
  217. $sql .= "`".$key."`='".$value."' AND ";
  218. }
  219. $sql = substr($sql, 0, -5);
  220. $consulta = $this->consulta($sql);//if ($tabla=='VUREGIS43')echo $sql;
  221. if (DEBUG_DB && $debug) echo $sql;
  222. if (!empty($this->Error)) {
  223. echo '<br/>Error al comprobar '.$tabla.':';
  224. $this->printLastErrorNumber();
  225. $this->printLastError();
  226. $this->printLastSQL();
  227. $this->rollbackTrans();
  228. }
  229. if ($datos = mysql_fetch_array($consulta)) return $datos['DATO'];
  230. return 0;
  231. }
  232.  
  233. function printLastErrorNumber() {
  234. if (DEBUG_DB) echo '<br/><b>Numero de error:</b> ' . $this->Errno;
  235. }
  236.  
  237. function printLastError() {
  238. if (DEBUG_DB) echo '<br/><b>Error:</b> ' . $this->Error;
  239. }
  240.  
  241. function printLastSQL() {
  242. if (DEBUG_DB) echo '<br/><b>SQL ejecutado:</b> ' . $this->ultimo_sql;
  243. }
  244.  
  245. }
  246. /** fin: clase DB_mysql **/

Report this snippet 

You need to login to post a comment.