Capitulos de este wiki
  1. 1 Clase PHP para tratar bases de datos MYSQL

Clase PHP para tratar bases de datos MYSQL - Clase PHP para tratar bases de datos MYSQL

1 - Clase PHP para tratar bases de datos MYSQL

Tutorial creado por joangarnet. Extraido de: http://www.joangarnet.com/blog/?p=28
15 de Septiembre de 2006

Aquí dejo una clase que hice hace tiempo para tratar bases de datos MYSQL.
Como extra lleva un par de métodos específicos para usar con Flash y uno para sacar info del server MYSQL de forma gráfica:

- result_par_valor_split() ( devuelve una cadena "Devuelve una cadena del tipo: id=1#2#5#3#4&title=Título 1#Título 2#Título 3# etc..." 
con los resultados de la consulta )
- result_par_valor_indx() Éste por Marcos Gonzalez ( Devuelve una cadena del tipo: "n_datos=5&id_0=1&title_0=Título 0&id_1=2&title_1=Título 2 etc..." )
- info () ( saca información de la consulta y del servidor MYSQL )

Además de lo fundamental:

- conectar ()
- escapar_chars () (añade contrabarras a los caracteres " '  )
- desescapar_chars () (la inversa del anterior)
- ejecutar_consulta () (ejecuta la cosulta en curso)
- result_num_filas () (devuelve el numero total de filas (horizontal) de la consulta)
- result_num_columnas () (devuelve el numero total de columnas (vertical) de la consulta)
- result_array_asoc () (devuelve un array asociativo de la consulta)
- cerrar_conexion () (cierra la conexión)

Aquí la clase:

PLAIN TEXT
PHP:
  1. <?php
  2.  
  3. /*
  4. * clase        ConsultaMysql
  5. * version    1.1
  6. * autor        Joan|Garnet http://www.joangarnet.com
  7. */
  8.  
  9.  
  10. class ConsultaMysql
  11. {
  12.     /////////////////////////
  13.     // PROPIEDADES PÚLICAS //
  14.     /////////////////////////
  15.    
  16.     var $servidor_mysql;    // direccion del servidor Mysql, normalmente es "localhost"
  17.     var $usuario;         // usuario del servidor Mysql
  18.     var $password;      // password del servidor Mysql
  19.     var $bbdd;        // nombre de la base de datos
  20.     var $consulta;      // aquí debes meter la consulta Mysql
  21.     var $separador;   /* si vas a usar el mdo result_par_valor_split(),
  22.                                 puedes asignar como separar los strings.
  23.                                 Por defecto se separan con "#"*/
  24.     var $testeando;   // true o false
  25.     var $email_admin;      /* si "$testeando" es false, entonces pon
  26.                                 el email del admin aqui para que reciba
  27.                                 notificaciones por email de los errores mysql */
  28.     var $resXML;            // para almacenar el resultado de la query en formato XML
  29.  
  30.     //////////////////////////
  31.     // PROPIEDADES PRIVADAS //
  32.     //////////////////////////
  33.    
  34.     var $conexion;
  35.     var $selec_bbdd;
  36.     var $string_sucio;
  37.     var $string_limpio;
  38.     var $resultado;
  39.     var $par_valor;
  40.     var $par_valor_split;
  41.     var $par_valor_indx;
  42.     var $largo_separador;
  43.     var $indice;
  44.     var $valor;
  45.     var $n_filas;
  46.     var $n_columnas;
  47.     var $fila;
  48.     var $arr_asoc;
  49.    
  50.    
  51.     /////////////////////////////
  52.     // CONSTRUCTOR DE LA CLASE //
  53.     /////////////////////////////
  54.    
  55.     function ConsultaMysql ()
  56.     {
  57.         $this->separador = "#";
  58.     }
  59.    
  60.     //////////////////////
  61.     // MÉTODOS PRIVADOS //
  62.     //////////////////////
  63.    
  64.     function err ()
  65.     {
  66.         if ($this-> testeando )
  67.         {
  68.             echo "<b><font color='red'>ERROR:</b> --> </b>" .
  69.             mysql_errno ()."</b> - <i>" .mysql_error ()."</i></font>";
  70.             exit ();
  71.         }
  72.         else
  73.         {
  74.             echo "<b><font color='red'>Ha habido un error</font></b>";
  75.             if ($this-> email_admin )
  76.             {
  77.                 echo ", el administrador ha sido informado por email";
  78.                 mail ($this-> email_admin ,
  79.                 "Error mysql en" .$_SERVER ['PHP_SELF'] ,
  80.                 "Error-> " .mysql_error ().
  81.                 "\n en->" .$_SERVER ['PHP_SELF'].$_SERVER ['QUERY_STRING'].
  82.                 "\n a las-> " .date ('H:i:s - D-d-m-Y'));
  83.             }
  84.             exit ();
  85.         }
  86.     }
  87.    
  88.     //////////////////////
  89.     // MÉTODOS PÚBLICOS //
  90.     //////////////////////
  91.    
  92.     function conectar ()
  93.     {
  94.         // conecta a la bbdd
  95.         $this-> conexion = @mysql_connect ($this-> servidor_mysql , $this-> usuario , $this-> password ) or $this-> err ();
  96.         $this-> selec_bbdd = @mysql_select_db ($this-> bbdd , $this-> conexion ) or $this-> err ();
  97.     }
  98.     function escapar_chars ()
  99.     {
  100.         // añade contrabarras a las palabras que lleven ' " \
  101.         $this-> string_limpio = addslashes ($this-> string_sucio );
  102.         return ($this-> string_limpio );
  103.     }
  104.     function desescapar_chars ()
  105.     {
  106.         // quita las contrabarras para mostrar el texto original con ' " \
  107.         $this-> string_limpio = stripslashes ($this-> string_sucio );
  108.         return ($this-> string_limpio );
  109.     }
  110.     function ejecutar_consulta ()
  111.     {
  112.         // ejecuta consulta Mysql
  113.         $this-> resultado = @mysql_query ($this-> consulta , $this-> conexion ) or $this-> err ($this-> resultado ) or $this-> err ();
  114.         return ($this-> resultado );
  115.     }
  116.     function result_num_filas ()
  117.     {
  118.         // devuelve el numero total de filas (horizontal) de la consulta
  119.         $this-> n_filas = mysql_num_rows ($this-> resultado );
  120.         return $this-> n_filas;
  121.     }
  122.     function result_num_columnas ()
  123.     {
  124.         // devuelve el numero total de columnas (vertical) de la consulta
  125.         $this-> n_columnas = mysql_num_fields ($this-> resultado );
  126.         return $this-> n_columnas;
  127.     }
  128.     function result_array_asoc ()
  129.     {
  130.         // devuelve un array asociativo de la consulta (por nombres de campo envez de por indice de campo)
  131.         while ($this-> fila = mysql_fetch_assoc ($this-> resultado ))
  132.         {
  133.             $this-> arr_asoc [] = $this-> fila;
  134.         }
  135.         return ($this-> arr_asoc );
  136.     }
  137.     function result_par_valor_split ()
  138.     {
  139.         // devuelve una cadena "var0=valor1,valor2,valor3&var1=valor1,valor2,valor3&var2= etc..." con los resultados de la consulta
  140.         $this-> result_array_asoc ();
  141.         $this-> par_valor = array ();
  142.         $this-> largo_separador = strlen ($this-> separador );
  143.         for ($k = 0; $k <sizeof ($this-> arr_asoc ); $k ++)
  144.         {
  145.             while ($this-> valor = current ($this-> arr_asoc [$k]) and $this-> indice = key (($this-> arr_asoc [$k])))
  146.             {
  147.                 if ( ! array_key_exists ($this-> indice , $this-> par_valor ))
  148.                 {
  149.                     $this-> par_valor [$this-> indice] = </SPAN>;</FONT></DIV>
    <LI style="FONT-WEIGHT: bold; COLOR: #26536a">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial><FONT size=2>                <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">}</SPAN></FONT></FONT></DIV>
    <LI style="FONT-WEIGHT: normal; COLOR: #3a6a8b; FONT-STYLE: normal; FONT-FAMILY: 'Courier New', Courier, monospace">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial size=2>                <SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">par_valor</SPAN> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">[</SPAN><SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">indice</SPAN><SPAN style="FONT-WEIGHT: bold; COLOR: #006600">]</SPAN> .= <SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">valor</SPAN> .<SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">separador</SPAN>;</FONT></DIV>
    <LI style="FONT-WEIGHT: bold; COLOR: #26536a">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT size=2><FONT face=Arial>                </FONT><SPAN style="COLOR: #000066"><FONT face=Arial>next</FONT></SPAN><FONT face=Arial> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">(</SPAN><SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">arr_asoc</SPAN> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">[</SPAN><SPAN style="COLOR: #0000ff">$k</SPAN><SPAN style="FONT-WEIGHT: bold; COLOR: #006600">]</SPAN><SPAN style="FONT-WEIGHT: bold; COLOR: #006600">)</SPAN>;</FONT></FONT></DIV>
    <LI style="FONT-WEIGHT: normal; COLOR: #3a6a8b; FONT-STYLE: normal; FONT-FAMILY: 'Courier New', Courier, monospace">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial><FONT size=2>            <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">}</SPAN></FONT></FONT></DIV>
    <LI style="FONT-WEIGHT: bold; COLOR: #26536a">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial><FONT size=2>        <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">}</SPAN></FONT></FONT></DIV>
    <LI style="FONT-WEIGHT: normal; COLOR: #3a6a8b; FONT-STYLE: normal; FONT-FAMILY: 'Courier New', Courier, monospace">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial><FONT size=2>        <SPAN style="COLOR: #616100">foreach</SPAN> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">(</SPAN><SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">par_valor</SPAN> <SPAN style="COLOR: #616100">as</SPAN> <SPAN style="COLOR: #0000ff">$indice</SPAN> => <SPAN style="COLOR: #0000ff">$valor</SPAN> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">)</SPAN></FONT></FONT></DIV>
    <LI style="FONT-WEIGHT: bold; COLOR: #26536a">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial><FONT size=2>        <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">{</SPAN></FONT></FONT></DIV>
    <LI style="FONT-WEIGHT: normal; COLOR: #3a6a8b; FONT-STYLE: normal; FONT-FAMILY: 'Courier New', Courier, monospace">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT face=Arial size=2>            <SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">par_valor_split</SPAN> .= <SPAN style="COLOR: #0000ff">$indice</SPAN> .<SPAN style="COLOR: #ff0000">"="</SPAN> .<SPAN style="COLOR: #0000ff">$valor</SPAN>;</FONT></DIV>
    <LI style="FONT-WEIGHT: bold; COLOR: #26536a">
    <DIV style="FONT-WEIGHT: normal; FONT-FAMILY: 'Courier New', Courier, monospace"><FONT size=2><FONT face=Arial>            <SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">par_valor_split</SPAN> = </FONT><SPAN style="COLOR: #000066"><FONT face=Arial>substr</FONT></SPAN><FONT face=Arial> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">(</SPAN><SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">par_valor_split</SPAN> , <SPAN style="COLOR: #800000">0</SPAN>, <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">(</SPAN></FONT><SPAN style="COLOR: #000066"><FONT face=Arial>strlen</FONT></SPAN><FONT face=Arial> <SPAN style="FONT-WEIGHT: bold; COLOR: #006600">(</SPAN><SPAN style="COLOR: #0000ff">$this</SPAN>-> <SPAN style="COLOR: #006600">par_valor_split</SPAN> </FONT></FONT></DIV></LI></OL><

1 opinión

Duda.

Sobre la funccion result_array_asoc
cuando realizas varias consultas, una tras otra, esta me regresa los valores anidados, es decir, si la primer consulta me regresa 3 resultados, cuando hago la segunda suma los de la primer consulta y los de la segunda y asi sucesivamente. Por que?.

Tutoriales relacionados con 'Clase PHP para tratar bases de datos MYSQL'

Aquí dejo una clase que hice hace tiempo para tratar bases de datos MYSQL.
PHPlib es un conjunto de clases que permiten de manera rápida y fácil manejar las... Más »

Autor y licencia de 'Clase PHP para tratar bases de datos MYSQL'


Tutorial de joangarnet. Extraido de: http://www.joangarnet.com/blog/?p=28 CopyLeft
Este contenido ha sido recopilado por el equipo de Wikilearning. Todo el contenido recopilado se ha obtenido respetando y comunicando en nuestro site la licencia de cada fuente.
Wikilearning tiene permiso expreso por escrito de los autores para publicar los contenidos que ha extraído de otras webs, incluyendo su uso comercial.