servidor = $servidor; $this->usuario = $usuario; $this->passwd = $password; $this->bd = $nombreBD; $this->conectar(); $this->auto_slashes = $auto_slashes; //AUTO! register_shutdown_function(array( &$this, "destructor" )); } /** * Destructor de la clase registrado en el constructor * */ function destructor(){ $this->desconectar(); unset( $this->bd,$this->conexion,$this->passwd,$this->servidor, $this->ultima_consulta,$this->ultimo_error,$this->usuario ); } /** * Cambia la propiedad de auto-activar addslashes() antes de consultar,por motivos de seguridad * * @param bool $estado */ function autoSlashes($estado){ $this->auto_slashes = $estado; } /** * Conecta a la base de datos devolviendo el resultado como true o false * * @param str $servidor * @param str $usuario * @param str $passwd * @param str $bd * @param bool $persistente * @return bool */ function conectar($servidor='', $usuario='', $passwd='', $bd='', $persistente=true) { // Abre una conexión con MySQL y selecciona la base de datos. Si cualquiera de los // parámtetros no están establecidos,le pasamos los datos por defecto. // Devuelve true en caso de conectar correctamente. if (!empty($servidor)) $this->servidor = $servidor; if (!empty($usuario)) $this->usuario = $usuario; if (!empty($passwd)) $this->passwd = $passwd; if (!empty($bd)) $this->bd= $bd; /* mysql_pconnect() actua como mysql_connect() con dos diferencias fundamentales. Primero, durante la conexión, la función intenta primero encontrar un enlace persistente abierto con el mismo host, usuario y password. Si lo encuentra, devuelve el identificador de enlace en lugar de abrir otra conexión. Segundo, la conexión no será cerrada cuando acabe la ejecución del script. El enlace permanecerá abierta para ser usado en el futuro (mysql_close() no cierra el enlace establecido con mysql_pconnect()). */ // Realizar la conexión... if ($persistente) $this->conexion = mysql_pconnect($this->servidor, $this->usuario, $this->passwd); else $this->conexion = mysql_connect($this->servidor, $this->usuario, $this->passwd); // Comprueba los errores producidos al realizar la conexión if (!$this->conexion) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } // Selecciona la BD if (!$this->seleccionar_bd($this->bd)) return false; $this->conectado = true; $this->establecerIdioma(); return true; // todo correcto } /** * Selecciona una base de datos devolviendo el resultado como booleano * * @param str $bd * @return bool */ function seleccionar_bd($bd='') { // Selecciona la base de datos $bd pasada como parámetro para ser usada. // Si el parámetro no está establecido se le pasa los valores por defecto // de la clase if (!empty($bd)) $this->bd = $bd; if (!mysql_select_db($this->bd)) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } return true; } /** * Establece el idioma de la base de datos como UTF8 para compatibilidad con el navegador en las consultas * */ function establecerIdioma(){ if(!@mysql_query('SET NAMES "UTF8"')) die("BD:1"); if(!@mysql_query("SET collation_server='utf8_bin'")) die("BD:2"); if(!@mysql_query("SET character_set_client='utf8'")) die("BD:3"); if(!@mysql_query("SET character_set_connection='utf8'")) die("BD:4"); if(!@mysql_query("SET character_set_results='utf8'")) die("BD:5"); if(!@mysql_query("SET character_set_server='utf8'")) die("BD:6"); if(!@mysql_query('set charset UTF8')) die("BD:7"); if(!@mysql_query('SET CHARACTER SET UTF8')) die("BD:8"); //if(!@mysql_query('SET COLLATION_CONNECTION="UTF8"')) die("BD:9"); } /** * Consulta de seleccion, devuelve el resultado de dicha consulta o false en caso de fallar. * * @param str $sql * @return array || false */ function seleccion($sql) { // Ejecuta una consulta SQL en la que se seleccionan datos que han de almacenarse // en el puntero r. Devuelve el éxito o fracaso de la ejecución de la consulta. $sql = "SELECT ".$sql; $this->ultima_consulta = $sql; //$this->establecerIdioma(); $r = mysql_query($sql); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } return $r; } /** * Realiza una consulta de un unico campo y un unico resultado * * @param str $sql * @return unknown */ function seleccion_unica($sql) { // Realiza una consulta SQL asumiendo que sólo se almacenará en el puntero $r una columna // , sólo existirá un resultado. // Devuelve el resultado del éxito o fracaso de la consulta. $sql = "SELECT ".$sql; $this->ultima_consulta = $sql; //$this->establecerIdioma(); $r = mysql_query($sql); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } if (mysql_num_rows($r) > 1 || mysql_num_rows($r) == 0) { $this->ultimo_error = "La consulta de un único resultado ha devuelto más de uno o ninguno."; return false; } $ret = mysql_result($r, 0); mysql_free_result($r); if ($this->auto_slashes) return stripslashes($ret); else return $ret; } /** * Toma un resultado de una seleccion (funcion seleccionar()) y devuelve la siguiente fila o tupla de la consulta * * @param array $resul * @param str $tipo * @return array */ function obtener_fila($resul, $tipo='MYSQL_BOTH') { // Devuelve una fila con datos desde el resulta de la consulta $resul. // Se usa en lugar de un típico: while($fila=mysql_fetch_array($r)). // Con ésta clase se utiliza : while($fila=$bd->obtener_fila($r)) // La razón principal es el poder utilizar la opción auto_slashes más tarde. if (!$resul) $this->mostrar_ultimo_error(true); if (mysql_num_rows($resul)==0) return false; if ($tipo == 'MYSQL_ASSOC') $fila = mysql_fetch_array($resul, MYSQL_ASSOC); if ($tipo == 'MYSQL_NUM') $fila = mysql_fetch_array($resul, MYSQL_NUM); if ($tipo == 'MYSQL_BOTH') $fila = mysql_fetch_array($resul, MYSQL_BOTH); if (!$fila) return false; if ($this->auto_slashes) { // Hacemos el recorte de comillas para cada campo de la consulta... foreach ($fila as $clave => $valor) { $fila[$clave] = stripslashes($valor); } } return $fila; } /** * Toma un solo resultado de una seleccion (funcion seleccionar()) y devuelve la primera fila o tupla de la consulta,libera la consulta despues * * @param array $resul * @param str $tipo * @return array */ function obtener_fila_unica(&$resul,$tipo='MYSQL_BOTH'){ if (!$resul) $this->mostrar_ultimo_error(true); if (mysql_num_rows($resul)==0) return false; if ($tipo == 'MYSQL_ASSOC') $fila = mysql_fetch_array($resul, MYSQL_ASSOC); if ($tipo == 'MYSQL_NUM') $fila = mysql_fetch_array($resul, MYSQL_NUM); if ($tipo == 'MYSQL_BOTH') $fila = mysql_fetch_array($resul, MYSQL_BOTH); if (!$fila) return false; if ($this->auto_slashes) { // Hacemos el recorte de comillas para cada campo de la consulta... foreach ($fila as $clave => $valor) { $fila[$clave] = stripslashes($valor); } } @mysql_free_result($resul); return $fila; } /** * Realiza una consulta y muestra informacion de depuracion de la misma.Devuelve false si la consulta no es correcta * * @param str $sql * @return bool */ function consulta_depurada($sql) { // Muy útil para el tiempo de desarrollo de páginas web. Simplemente muestra // una consutla por pantalla usando una . $r = $this->seleccion($sql); //Realiza la seleccion de múltiples campos: if (!$r) return false; echo "
\n"; echo "
\n"; $i = 0; while ($fila = mysql_fetch_assoc($r)) { if ($i == 0) { echo "\n"; echo "\n"; foreach ($fila as $col => $valor) { echo "\n"; } echo "\n"; } $i++; if ($i % 2 == 0) $bg = '#E3E3E3'; else $bg = '#F3F3F3'; echo "\n"; foreach ($fila as $valor) { echo "\n"; } echo "\n"; } echo "
$sql
$col
$valor
\n"; return true; } /** * Realiza una consulta de insercion de datos devolviendo el identificador nuevo * * @param str $sql * @return int */ function insertar($sql) { // Inserta los datos en la BD por medio del comando insert de la consulta $sql. // Devuelve el id de la inserción o verdadero(true) si no existe ningún campo // en la tabla que se autoincremente. Falso si ocurrió algun error. $sql = "INSERT INTO ".$sql; $this->ultima_consulta = $sql; $r = mysql_query($sql); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } $id = mysql_insert_id(); if ($id == 0) return true; else return $id; } /** * Realiza una consulta de actualizacion o Update() devolviendo falso en caso de error o el numero de registros afectados en otro caso * * @param str $sql * @return unknown */ function actualizar($sql) { // Realiza una consulta UPDATE por medio del comando de $sql . // Devuelve las filas afectadas o true si no se necesitó actualizar nada. // Devuelve falso (false) si ocurrió un error. $sql = "UPDATE ".$sql; $this->ultima_consulta = $sql; $r = mysql_query($sql); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } $filas = mysql_affected_rows(); if ($filas == 0) return true; // ninguna fila actualizada else return $filas; } /** * Inserta una serie de consultas en una tabla * * @param str $tabla * @param array $matriz * @return bool */ function insertar_matriz($tabla, $matriz) { // Inserta una fila en la BD desde un par de valores llave->valor de una matriz. // Dicha matriz debe tener los nombres de los campos o columnas de la tabla. // Devuelve el id de la inserción o true si no hay ningún campo auto_increment // en la tabla. Falso en caso de error. if (empty($matriz)) { $this->ultimo_error = "Se debe pasar una matriz (array) con los nombres de los campos de la tabla y sus valores, a la función the insertar_matriz()."; if ($this->debug) $this->mostrar_ultimo_error(); return false; } $cols = '('; $valores = '('; foreach ($matriz as $clave=>$valor) { // itera entre los valores de entrada $cols .= "$clave,"; $tipo_col = $this->tipo_columna($tabla, $clave); if (!$tipo_col) return false; // error obteniendo el tipo de campo con la $clave de la $tabla // determina si se necesita separar el valor en distintas cláusulas if (substr_count(MYSQL_TIPOS_NUMERICOS, "$tipo_col ")) $valores .= "$valor,"; elseif (substr_count(MYSQL_TIPOS_FECHA, "$tipo_col ")) { $valor = $this->formatear_datetime($valor, $tipo_col); // formato fecha (datetime) $valores .= "'$valor',"; } elseif (substr_count(MYSQL_TIPOS_CADENA, "$tipo_col ")) { if ($this->auto_slashes) $valor = addslashes($valor); $valores .= "'$valor',"; } } $cols = rtrim($cols, ',').')'; $valores = rtrim($valores, ',').')'; // insertar los valores $sql = "$tabla $cols VALUES $valores"; return $this->insertar($sql); } /** * Realiza una serie de consultas de actualizacion * * @param str $tabla * @param array $matriz * @param str $condicion * @return bool || int */ function actualizar_matriz($tabla, $matriz, $condicion) { // Actualiza tuplas de una $tabla mediante el uso de una $matriz y una $condicion. La // $matriz pasada ha de tener llaves y valores de las columnas de la $tabla. // $condicion es basicamente una cláusula WHERE (sin el WHERE). // Ej.: "columna=valor AND columna2='otro valor'" debería ser una condición. // Devuelve las columnas afectadas o verdadero si no se actualizó ninguna. // Devuelve falso en caso de haber ocurrido un error. if (empty($matriz)) { $this->ultimo_error = "Se debe pasar una matriz(array) con a la función actualizar_matriz()."; if ($this->debug) $this->mostrar_ultimo_error(); return false; } $sql = "UPDATE $tabla SET"; foreach ($matriz as $clave=>$valor) { // iterata entre los valores de entrada $sql .= " $clave="; $tipo_col = $this->tipo_columna($tabla, $clave); if (!$tipo_col) return false; // error al obtener el tipo de campo // determina si se necesita separar los valores en cláusulas if (substr_count(MYSQL_TIPOS_NUMERICOS, "$tipo_col ")) $sql .= "$valor,"; elseif (substr_count(MYSQL_TIPOS_FECHA, "$tipo_col ")) { $valor = $this->formatear_datetime($valor, $tipo_col); // formateo del tipo datetime $sql .= "'$valor',"; } elseif (substr_count(MYSQL_TIPOS_CADENA, "$tipo_col ")) { if ($this->auto_slashes) $valor = addslashes($valor); $valores .= "'$valor',"; } } $sql = rtrim($sql, ','); // quita la coma que sobre if (!empty($condicion)) $sql .= " WHERE $condicion"; // actualiza los valores return $this->actualizar($sql); } /** * Realiza un consulta de borrado y devuelve false en caso de error o el numero de filas borradas en otro caso * * @param str $sql * @return bool || int */ function borrar($sql){ $sql = "DELETE FROM ".$sql; $this->ultima_consulta = $sql; $r = mysql_query($sql); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } $filas = mysql_affected_rows(); if ($filas == 0) return true; // ninguna fila actualizada else return $filas; } /** * Ejecuta un fichero de consultas * * @param str $fichero * @return bool */ function ejecutar_fichero ($fichero) { // ejecuta un fichero con comandos SQL. if (!file_exists($fichero)) { $this->ultimo_error = "El fichero $fichero no existe."; if ($this->debug) $this->mostrar_ultimo_error(); return false; } $str = file_get_contents($fichero); if (!$str) { $this->ultimo_error = "No se puede leer el fichero $fichero."; if ($this->debug) $this->mostrar_ultimo_error(); return false; } $this->ultima_consulta = $str; // Separa con split todas las consultas del fichero en un array $sql = explode(';', $str); foreach ($sql as $query) { if (!empty($query)) { $r = mysql_query($query); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } } } return true; } /** * Devuelve el tipo de columna de un campo de una tabla * * @param str $tabla * @param str $campo * @return str */ function tipo_columna($tabla, $campo) { // Obtiene información acerca de un $campo en particular usando mysql_fetch_field // Devuelve un array con la información de la columna de la $tabla o false si // ocurre un error. $r = mysql_query("SELECT $campo FROM $tabla LIMIT 1"); if (defined('BD_CONTAR_CONSULTAS')) $this->consultas++; if (!$r) { $this->ultimo_error = mysql_error(); if ($this->debug) $this->mostrar_ultimo_error(); return false; } $ret = mysql_field_type($r, 0); if (!$ret) { $this->ultimo_error = "No se pudo obtener la información de $tabla.$campo."; if ($this->debug) $this->mostrar_ultimo_error(); mysql_free_result($r); return false; } mysql_free_result($r); return $ret; } /** * Establece el formato de una fecha para consultar correctamente * * @param date $valor * @param str $tipo * @return date */ function formatear_datetime($valor, $tipo='') { // Devuelve la fecha pasada como $valor en un formato de entrada para la BD. Puede pasarse // esta función un valor de 'timestamp' como puede ser time() o una cadena // como '04/14/2003 5:13 AM'. if (gettype($valor) == 'string') $valor = strtotime($valor); if (!empty($tipo)) return date($tipo, $valor); else return date('Y-m-d H:i:s', $valor); } /** * Escribe por pantalla la ultmia consulta con error ,el codigo SQL se muestra si $mostrar_consulta es true * * @param bool $mostrar_consulta */ function mostrar_ultimo_error($mostrar_consulta=true) { // Muestra por pantalla el último error en un formato determinado. // Si $mostrar_consulta es true, entonces la última consulta que fue ejecutada // también es mostrada. ?>
bd.class.php Error:
ultimo_error ?>
ultima_consulta))) { $this->mostrar_ultima_consulta(); } } /** * Devuelve el HTML * */ function devolver_ultimo_error(){ return '
bd.class.php Error:
'.$this->ultimo_error.'
'.$this->devolver_ultima_consulta(); } /** * Devuelve el texto de la ultima consulta * */ function devolver_ultima_consulta(){ return '
Última consulta SQL:
'.str_replace("\n", '
', $this->ultima_consulta).'
'; } /** * Muestra el codigo SQL de la ultima consulta ejecutada * */ function mostrar_ultima_consulta() { // Muestra por pantalla la última consulta que fue ejecutada mediante una caja con divisiones
echo $this->devolver_ultima_consulta(); } /** * Desconecta de la base de datos,para el destructor tambien ;-) * */ function desconectar(){ @mysql_close($this->conexion); } } ?>