304 lines
10 KiB
PHP
Executable File
304 lines
10 KiB
PHP
Executable File
<?php
|
||
if (!defined('entry') || !entry) {
|
||
die('Not a valid page');
|
||
}
|
||
/**
|
||
* version 0.0.1
|
||
*
|
||
* Clase Conexion_Mysql
|
||
*
|
||
* @name Manejo de la conexion a la BD.
|
||
* @version 0.0.1
|
||
* @link http://www.pecesama.net/weblog/
|
||
* @copyright MIT Licence
|
||
* @author Pedro Santana [pecesama]
|
||
*/
|
||
|
||
// constantes
|
||
define('MYSQL_TYPES_NUMERIC', 'int real ');
|
||
define('MYSQL_TYPES_DATE', 'datetime timestamp year date time ');
|
||
define('MYSQL_TYPES_STRING', 'string blob ');
|
||
|
||
class Conexion_Mysql
|
||
{
|
||
public $mbase_datos;
|
||
public $mservidor;
|
||
public $musuario;
|
||
public $mclave;
|
||
public $mid_conexion = 0; // Identificador de conexi<78>n
|
||
public $mid_consulta = 0; // Identificador de consulta
|
||
public $merror_numero = 0; // N<>mero de error
|
||
public $merror = ""; // Descripci<63>n del error.
|
||
|
||
/** Al crear una instancia de clase, se ejecutara esta funcion */
|
||
public function __construct($bd="", $host="localhost", $user="", $pass="")
|
||
{
|
||
$this->mbase_datos = $bd;
|
||
$this->mservidor = $host;
|
||
$this->musuario = $user;
|
||
$this->mclave = $pass;
|
||
|
||
if (!$this->conectar()) {
|
||
$mensaje = "
|
||
<h3 class=\"important\">Error establishing a database connection</h3>
|
||
<p>This either means that the username and password information in your <code>config.php</code> file is incorrect or we can't contact the database server at localhost. This could mean your host's database server is down.</p>
|
||
<ul>
|
||
<li>Are you sure you have the correct username and password?</li>
|
||
<li>Are you sure that you have typed the correct hostname?</li>
|
||
<li>Are you sure that the database server is running?</li>
|
||
</ul>";
|
||
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<78>n
|
||
}
|
||
|
||
/** Para ejecutar consultas en la conexi<78>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();
|
||
die(var_dump($this->merror));
|
||
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 $ret;
|
||
}
|
||
|
||
/**
|
||
* 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<72> 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 "<table border=1>\n";
|
||
// mostramos los nombres de los campos
|
||
for ($i = 0; $i < $this->contarCampos(); $i++) {
|
||
echo "<td><b>".$this->obtenerNombreCampo($i)."</b></td>\n";
|
||
}
|
||
echo "</tr>\n";
|
||
// mostrarmos los registros
|
||
while ($row = $this->mid_consulta->fetch(PDO::FETCH_NUM)) {
|
||
echo "<tr> \n";
|
||
for ($i = 0; $i < $this->contarCampos(); $i++) {
|
||
echo "<td>".$row[$i]."</td>\n";
|
||
}
|
||
echo "</tr>\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
|