mbase_datos = $bd; $this->mservidor = $host; $this->musuario = $user; $this->mclave = $pass; if (!$this->conectar()) { $mensaje = "

Error establishing a database connection

This either means that the username and password information in your config.php file is incorrect or we can't contact the database server at localhost. This could mean your host's database server is down.

"; die($mensaje); } } /** Conectar a la base de datos */ public function conectar() { // Conectamos al servidor try { $this->mid_conexion = new PDO("mysql:host=$this->mservidor;dbname=$this->mbase_datos;charset=utf8", $this->musuario, $this->mclave); } catch (Exception $e) { $this->merror = $e->getMessage(); return false; } return $this->mid_conexion; // Si todo salio bien regresa el id de la conexi�n } /** Para ejecutar consultas en la conexi�n abierta */ public function ejecutarConsulta($msql = "") { if (empty($msql)) { $this->merror = "No SQL statement entered"; return false; } //ejecutamos la consulta $this->mid_consulta = $this->mid_conexion->query($msql); if (!$this->mid_consulta) { $this->merror_numero = $this->mid_conexion->errorCode(); $this->merror = $this->mid_conexion->errorInfo(); return false; } return $this->mid_consulta; // Si todo salio bien regresa el id de la consulta } /** * Inserta un registro en la DB por cada llave->valor en un arreglo. * No se debe usar sentencias SQL con esta funcion. * Para usar sentencias SQL se debe utilizar ejecutarConsulta(). * * @param mixed $tabla El nombre de la tabla en la BD. * @param array $datos Arreglo con los campos que se desean insertar $arreglo['campo'] = 'valor'. * @return string El ID del insert, verdadero si la tabla no tiene un campo auto_increment o false si ocurre un error. */ public function insertarDeFormulario($tabla, $datos) { if (empty($datos)) { $this->merror = "Debes de pasar un arreglo como parametro."; return false; } $cols = '('; $sqlValues = '('; foreach ($datos as $llave=>$valor) { $cols .= "$llave,"; $tipo_col = $this->obtenerTipoCampo($tabla, $llave); // obtiene el tipo de campo if (!$tipo_col) { return false; } // error! // determina si se necesita poner comillas al valor. if (is_null($valor)) { $sqlValues .= "NULL,"; } elseif (substr_count(MYSQL_TYPES_NUMERIC, "$tipo_col ")) { $sqlValues .= "$valor,"; } elseif (substr_count(MYSQL_TYPES_DATE, "$tipo_col ")) { $valor = $this->formatearFecha($valor, $tipo_col); // formatea las fechas $sqlValues .= "'$valor',"; } elseif (substr_count(MYSQL_TYPES_STRING, "$tipo_col ")) { $valor = $this->sql_escape($valor); $sqlValues .= "$valor,"; } } $cols = rtrim($cols, ',').')'; $sqlValues = rtrim($sqlValues, ',').')'; // inserta los valores en la DB $sql = "INSERT INTO $tabla $cols VALUES $sqlValues"; return $this->ejecutarConsulta($sql); } /** * Modifica un registro en la DB por cada llave->valor en un arreglo. * No se debe usar sentencias SQL con esta funcion. * Para usar sentencias SQL se debe utilizar ejecutarConsulta(). * * @param mixed $tabla El nombre de la tabla en la BD. * @param array $datos Arreglo con los campos que se desean insertar $arreglo['campo'] = 'valor'. * @param mixed $condicion Es basicame una clausula WHERE (sin el WHERE). Por ejemplo, * "columna=valor AND columna2='otro valor'" seria una condicion. * @return string El numero de registros afectados o verdadero si no necesitaba actualizarse el registro. * Falso si ocurrio algun error. */ public function modificarDeFormulario($tabla, $datos, $condicion="") { if (empty($datos)) { $this->merror = "Debes de pasar un arreglo como parametro."; return false; } $sql = "UPDATE $tabla SET"; foreach ($datos as $llave=>$valor) { $sql .= " $llave="; $tipo_col = $this->obtenerTipoCampo($tabla, $llave); // obtiene el tipo de campo if (!$tipo_col) { return false; } // error! // determina si se necesita poner comillas al valor. if (is_null($valor)) { $sql .= "NULL,"; } elseif (substr_count(MYSQL_TYPES_NUMERIC, "$tipo_col ")) { $sql .= "$valor,"; } elseif (substr_count(MYSQL_TYPES_DATE, "$tipo_col ")) { $valor = $this->formatearFecha($valor, $tipo_col); /// formatea las fechas $sql .= "'$valor',"; } elseif (substr_count(MYSQL_TYPES_STRING, "$tipo_col ")) { $valor = $this->sql_escape($valor); $sql .= "$valor,"; } } $sql = rtrim($sql, ','); // elimina la ultima coma if (!empty($condicion)) { $sql .= " WHERE $condicion"; } // modifica los valores return $this->ejecutarConsulta($sql); } /** * Obtiene la informacion sobre un campo usando la funcion mysql_fetch_field. * * @param mixed $tabla El nombre de la tabla en la BD. * @param string $campo El campo del que se desea la informacion. * @return array Un arreglo con la informacion del campo o false si hay algun error. */ public function obtenerTipoCampo($tabla, $campo) { $r = $this->mid_conexion->query("SELECT $campo FROM $tabla"); if (!$r) { $this->merror = $this->mid_conexion->errorInfo(); return false; } $ret = $r->getColumnMeta(0); if (!$ret) { $this->merror = "Field information cannot be obtained : ".$tabla.$campo."."; $r->closeCursor(); return false; } $r->closeCursor(); return strtolower($ret['native_type']); } /** * Convierte una fecha en formato para DB. * * @param mixed $valor Se le puede pasar un valor timestamp como time() o un string como '04/14/2003 5:13 AM'. * @return date Fecha para insertar en la BD. */ public function formatearFecha($valor) { if (!preg_match("/^.{4}\-.{2}\-.{2}\ .{2}\:.{2}\:.{2}$/i", $valor)) { if (preg_match("/^([0-9]+)$/i", $valor)) { $valor = date("Y-m-d H:i:s", $valor); } else { // Estari� en el formato strtotime() $valor = date("Y-m-d H:i:s", strtotime($valor)); } } return $valor; /* if (gettype($valor) == 'string') $valor = strtotime($valor); return date('Y-m-d H:i:s', $valor); */ } /** * Obtiene el registro obtenido de una consulta. */ public function obtenerRegistro() { return $this->mid_consulta->fetch(PDO::FETCH_ASSOC); } /** * Devuelve el n�mero de campos de una consulta. */ public function contarCampos() { return $this->mid_consulta->columnCount(); } /** * Devuelve el n�mero de registros de una consulta. */ public function contarRegistros() { return @$this->mid_consulta->rowCount(); } /** * Devuelve el nombre de un campo de una consulta. */ public function obtenerNombreCampo($numero_campo) { return $this->mid_consulta->getColumnMeta($numero_campo); } /** * Muestra los datos de una consulta (para debug). */ public function verConsulta() { echo "\n"; // mostramos los nombres de los campos for ($i = 0; $i < $this->contarCampos(); $i++) { echo "\n"; } echo "\n"; // mostrarmos los registros while ($row = $this->mid_consulta->fetch(PDO::FETCH_NUM)) { echo " \n"; for ($i = 0; $i < $this->contarCampos(); $i++) { echo "\n"; } echo "\n"; } } /** * Cierra la conexion a la BD. */ public function cierraConexion() { $this->mid_consulta->closeCursor(); } public function sql_escape($value) { if (get_magic_quotes_gpc()) { $value = stripslashes($value); } if (method_exists("PDO", "quote")) { $value = $this->mid_conexion->quote($value); } else { $value = addslashes($value); } return $value; } } //fin de la Clase conexion_mysql
".$this->obtenerNombreCampo($i)."
".$row[$i]."