Retroceder   Foros del Web > Programación para sitios web > PHP > PHP orientado a objetos

Respuesta
 
Herramientas Desplegado
Antiguo 23-ene-2005, 13:27   #1 (permalink)
Reynier está en el buen camino
 
Avatar de Reynier
 
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.842
Enviar un mensaje por ICQ a Reynier Enviar un mensaje por MSN a Reynier Enviar un mensaje por Yahoo  a Reynier
Clase para usar con BDatos Parte1

Bueno está fue una clase que me encontré un poco incompleta en Internet y la bajé y le hice modificaciones para que trabajara con MSSQL. Estoy estudiando un poco más para poder extenderla a Oracle y a Firebird. La tengo que picar en partes porque el Foro no me deja publicar mensajes muy extensos.
Parte 1: Fijarse que todo pertenece a la clase EasySQL por lo que el parentesis de la clase EasySQL cierra al final de todo.
Código PHP:
<?php
 
class EasySQL{
  var 
$SQLDatabase// (objeto)   Tipo Mixto. Puede tener instancias diferentes dependiendo del SGBD usado
  
var $SQLQuery;    // (objeto)   Crea consultas SQL de tipo: SQLQuery
  
var $connection;  // (recurso)  Conección con la BDatos
  
var $result;      // (recurso)  Recurso identificativo retornado por la clausula SELECT, o booleano si las clausulas fueron INSERT, UPDATE o DELETE
  
var $total_rows;  // (valor)    Número de filas seleccionadas o afectadas (INSERT, UPDATE, DELETE) por la última consulta ejecutada

  
function EasySQL($SQLDatabase ""$host ""$user ""$password ""$db_name ""$port ""){
   
$_default['SQLDatabase'] = "";          //  SGBD por defecto (Ejemplo: "MySQL", "PostGreSQL", "SQLite", "SQL")
   
$_default['host']        = "localhost"//  Servidor o Host donde se haya hospedada la BDatos
   
$_default['user']        = "root";      //  Usuario de conexión a la BDatos
   
$_default['password']    = "";          //  Contraseña para acceder a la BDatos
   
$_default['db_name']     = "";          //  BDatos que será seleccionada
   
$_default['port']        = "";          //  Puerto de acceso a el SGBD. Dejar en blanco para usar el que trae la clase por defecto
   
   
$SQLDatabase = ($SQLDatabase != "")  ?  (string)$SQLDatabase  :  $_default['SQLDatabase'];
   
$host        = ($host != "")         ?  (string)$host         :  $_default['host'];
   
$user        = ($user != "")         ?  (string)$user         :  $_default['user'];
   
$password    = ($password != "")     ?  (string)$password     :  $_default['password'];
   
$db_name     = ($db_name != "")      ?  (string)$db_name      :  $_default['db_name'];
   
$port        = ($port != "")         ?  (int)$port            :  $_default['port'];
   
   
$this->SQLQuery = new SQLQuery();
   if(
preg_match("/^(0|mysql)$/i",trim($SQLDatabase))){
   
// MySQL
    
if (!function_exists("mysql_connect")){
     
$this->error("Librería MySQL no encontrada.");
     return 
false;
    }else if(!
class_exists("MySQL")){
     
$this->error("No se ha podido cargar la clase <strong>MySQL</strong>. Abortando <strong>" __CLASS__ "</strong> ejecución de la clase.");
     return 
false;
    }
    
$this->SQLDatabase = new MySQL($host$user$password$db_name$port);
   }else if(
preg_match("/^(1|pg|postgre(s|sql)?)$/i",trim($SQLDatabase))){
   
// PostGreSQL
    
if (!function_exists("pg_connect")){
     
$this->error("Librería PostGreSQL no encontrada.");
     return 
false;
    }else if (!
class_exists("PostGreSQL")){
     
$this->error("No se ha podido cargar la clase <strong>PostGreSQL</strong>. Abortando ejecución de la clase <strong>" __CLASS__ "</strong>.");
     return 
false;
    }
     
$this->SQLDatabase = new PostGreSQL($host$user$password$db_name$port);
   }else if (
preg_match("/^(2|sqlite)$/i",trim($SQLDatabase))){
   
// SQLite
    
if (!function_exists("sqlite_open")){
     
$this->error("Librería SQLite no encontrada.");
     return 
false;
    }else if (!
class_exists("SQLite")){
     
$this->error("No se ha podido cargar la clase <strong>SQLite</strong>. Abortando ejecución de la clase <strong>" __CLASS__ "</strong>.");
     return 
false;
    }
     
$this->SQLDatabase = new SQLite($host$user$password$db_name$port);
   }else if (
preg_match("/^(2|sql)$/i",trim($SQLDatabase))){
   
// SQL Server
    
if (!function_exists("sql_open")){
     
$this->error("Librería SQL no encontrada.");
     return 
false;
    }else if (!
class_exists("SQL")){
     
$this->error("No se ha podido cargar la clase <strong>SQL</strong>. Abortando ejecución de la clase <strong>" __CLASS__ "</strong>.");
     return 
false;
    }
     
$this->SQLDatabase = new SQL($host$user$password$db_name$port);
   }else{
    
$this->error("No se ha definido el tipo de Bases de Datos! Abortando ejecución de la clase <strong>" __CLASS__ "</strong>.");
    return 
false;
   }

   
$this->connection false;
   
$this->result     false;
   
$this->total_rows 0;
  }

  function 
connect($db_name ""){
   
$db_name = ($db_name != "")?$db_name:$this->SQLDatabase->db_name;
   
$this->SQLDatabase->connect($this->connection$db_namefalse);
   return 
$this->connection;
  }

  function 
pconnect($db_name ""){
   
$db_name = ($db_name != "")?$db_name:$this->SQLDatabase->db_name;
   
$this->SQLDatabase->connect($this->connection$db_nametrue);
   return 
$this->connection;
  }

  function 
disconnect(){
   return 
$this->SQLDatabase->disconnect($this->connection);
  }

  function 
close(){
   return 
$this->disconnect();
  }

  function 
query($query){
   
$was_connected    true;
   
$this->result     false;
   
$this->total_rows 0;
   if(!
$this->connection){
    
$was_connected false;
     if(!
$this->connect()){
      
$this->error();
      return 
false;
     }
   }
   
$this->result $this->SQLDatabase->query($query$this->connection);
   if(!
$this->result){
    
$this->error();
    return 
false;
   }
   if(
is_bool($this->result)){
    
$this->total_rows $this->SQLDatabase->affectedRows($this->result$this->connection);
   }
   if(!
$was_connected){
    
$this->disconnect();
   }
   return 
$this->result;
  }

  function 
fetchArray($result=""){
   if(
$result==""){
    
$result = &$this->result;
   }
   return 
$this->SQLDatabase->fetchArray($result);
  }

  function 
fetchRow($result=""){
   if(
$result==""){
    
$result = &$this->result;
   }
   return 
$this->SQLDatabase->fetchRow($result);
  }

  function 
fetchAssoc($result=""){
   if (
$result==""){
    
$result = &$this->result;
   }
   return 
$this->SQLDatabase->fetchAssoc($result);
  }

  function 
error($message=""){
   if(
$message==""){
    
$message $this->SQLDatabase->error($this->connection);
   }
   echo 
'<br /><span style="padding: 1px 7px 1px 7px; background-color: #ffd7d7; font-family: verdana; color: #000000; font-size: 13px;"><span style="color: #ff0000; font-weight: bold;">Error!</span> ' $message '</span><br />';
  }

  function 
useDatabase($db_name){
   
$this->SQLDatabase->db_name = (string)$db_name;
  }

  function 
useTable($table){
   
$this->SQLQuery->table = (string)$table;
  }

  function 
setFieldValue($field,$value,$is_sql_function=false){
   
$field = (string)$this->SQLDatabase->escape($field);
   
$value = (string)$this->SQLDatabase->escape($value);
   
$this->SQLQuery->values[$field]['value']           = $value;
   
$this->SQLQuery->values[$field]['is_sql_function'] = (bool)$is_sql_function;
  }

  function 
setWhere($where){
   
$this->SQLQuery->where = (string)$where;
  }

  function 
setLimit($limit){
   
$this->SQLQuery->limit = (string)$limit;
  }

  function 
setSelection($selection){
   
$this->SQLQuery->selection = (string)$selection;
  }

  function 
select(){
   
$no_limit_query $this->SQLQuery->createSelect(false);
   
$return_query   $this->SQLQuery->createSelect();
   
$result         $this->query($return_query);
   if(!
$result){
    return 
false;
   }
   
$this->total_rows $this->SQLDatabase->numRows($this->query($no_limit_query));
   return 
$result;
  }

  function 
Insert(){
   return 
$this->query($this->SQLQuery->createInsert());
  }

  function 
Update(){
   return 
$this->query($this->SQLQuery->createUpdate());
  }

  function 
Delete(){
   return 
$this->query($this->SQLQuery->createDelete());
  }

  function 
Truncate(){
   return 
$this->query($this->SQLQuery->createTruncate());
  }
 }
__________________
Ing. Reynier Pérez Mira
Reynier está desconectado   Responder Citando
Antiguo 23-ene-2005, 13:30   #2 (permalink)
Reynier está en el buen camino
 
Avatar de Reynier
 
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.842
Enviar un mensaje por ICQ a Reynier Enviar un mensaje por MSN a Reynier Enviar un mensaje por Yahoo  a Reynier
Parte 2

Código PHP:
 class SQLQuery{
  var 
$query;     // (string)  Última consulta creada
  
var $table;     // (string)  Tabla usada
  
var $values;    // (array)   Cada elemento es un nuevo arreglo con llaves que son los nombres de los campos. Cada nuevo arreglo contiene los elementos: (string) "value" y (bool) "is_sql_function"
  
var $where;     // (string)  clausula "WHERE"
  
var $limit;     // (string)  clausula "LIMIT"
  
var $selection// (string)  Selección de la clausula SELECT: "SELECT (selection) FROM table;"

  
function SQLQuery(){
   
$this->query "";
   
$this->table        "";
   
$this->values       = array();
   
$this->where        "";
   
$this->limit        "";
   
$this->selection    "*";
  }

  function 
createSelect($use_limit_clause true){
   if(
$this->selection==""  ||  $this->table==""){
    if(
$use_limit_clause){
     if(
$this->selection==""){
      
$this->error('No se ha podido ejecutar la consulta "SELECT". El parámetro <strong>"selección"</strong> está vacío.');
     }
     if(
$this->table==""){
      
$this->error('No se ha podido ejecutar la consulta "SELECT". El parámetro <strong>"tabla"</strong> está vacío.');
     }
    }
    return 
false;
   }

   
$this->query  "SELECT " $this->selection " FROM " $this->table $this->returnWhere();
   
$this->query .= ($use_limit_clause)  ?  $this->returnLimit()  :  "";
   return 
$this->query;
  }

  function 
createInsert(){
   if(
$this->table==""  ||  count($this->values)==0){
    if(
$this->table=="") {
     
$this->error('No se ha podido ejecutar la consulta "INSERT". El parámetro <strong>"tabla"</strong> está vacío.');
    }
    if (
count($this->values) == 0) {
     
$this->error('No se ha podido ejecutar la consulta "INSERT". El parámetro <strong>"valores (VALUES)"</strong> está vacío.');
    }
    return 
false;
   }
   
$values $fields = array();
   foreach(
$this->values as $fieldName => $fieldSettings){
    
$fields[] = $fieldName;
    if (
$fieldSettings['value']===NULL){
     
$values[] = "NULL";
    }else if(
$fieldSettings['is_sql_function']){
     
$values[] = $fieldSettings['value'];
    }else{
     
$values[] = "'" $fieldSettings['value'] . "'";
    }
   }
   
$values " (" .   implode(', '$fields)   . ") VALUES (" .   implode(', '$values)   . ")";
   
$this->query "INSERT INTO " $this->table $values;
   return 
$this->query;
  }

  function 
createUpdate(){
   if (
$this->table == ""  ||  count($this->values) == 0  ||  $this->where == ""){
    if (
$this->table == ""){
     
$this->error('No se ha podido ejecutar la consulta "UPDATE". El parámetro <strong>"tabla"</strong> está vacío.');
    }
    if (
count($this->values) == 0){
     
$this->error('No se ha podido ejecutar la consulta "UPDATE". El parámetro <strong>"valores (VALUES)"</strong> está vacío.');
    }
    if (
$this->where == "") {
     
$this->error('Safety procedure: La consulta "UPDATE" no ha sido ejecutada porque la clausula <strong>"WHERE"</strong> está vacía.');
    }
    return 
false;
   }
   
$values $fields = array();
   foreach(
$this->values as $fieldName => $fieldSettings){
    if(
$fieldSettings['value'] === NULL){
     
$values[] = $fieldName " = NULL";
    }else if(
$fieldSettings['is_sql_function']){
     
$values[] = $fieldName " = " $fieldSettings['value'];
    }else{
     
$values[] = $fieldName " = '" $fieldSettings['value'] . "'";
    }
   }
   
$values " SET " .   implode(', '$values);
   
$this->query "UPDATE " $this->table $values $this->returnWhere() . $this->returnLimit();
   return 
$this->query;
  }

  function 
createDelete(){
   if(
$this->table == ""  ||  $this->where == ""){
    if (
$this->table == ""){
     
$this->error('No se ha podido ejecutar la consulta "DELETE". El parámetro <strong>"tabla"</strong> está vacío.');
    }
    if (
$this->where == ""){
     
$this->error('Safety procedure: "DELETE" query was not created because <strong>"where"</strong> clause was empty.');
    }
    return 
false;
   }
   
$this->query "DELETE FROM " $this->table $this->returnWhere() . $this->returnLimit();
   return 
$this->query;
  }

  function 
createTruncate(){
   if (
$this->table == ""){
    
$this->error('No se ha podido ejecutar la consulta "TRUNCATE". El parámetro <strong>"tabla"</strong> está vacío.');
    return 
false;
   }
   
$this->query "TRUNCATE TABLE " $this->table;
   return 
$this->query;
  }

  function 
returnWhere(){
   
$where = ($this->where != "")  ?  (" WHERE (" $this->where ")")  :  "";
   return 
$where;
  }

  function 
returnLimit(){
   
$limit = ($this->limit != "")  ?  (" LIMIT " $this->limit)  :  "";
   return 
$limit;
  }

  function 
error($message ""){
   echo 
'<br /><span style="padding: 1px 7px 1px 7px; background-color: #ffd7d7; font-family: verdana; color: #000000; font-size: 13px;"><span style="color: #ff0000; font-weight: bold;">Error!</span> ' $message '</span><br />';
  }
 } 
__________________
Ing. Reynier Pérez Mira
Reynier está desconectado   Responder Citando
Antiguo 23-ene-2005, 13:31   #3 (permalink)
Reynier está en el buen camino
 
Avatar de Reynier
 
Fecha de Ingreso: noviembre-2002
Ubicación: Por ahí en algún sitio
Mensajes: 1.842
Enviar un mensaje por ICQ a Reynier Enviar un mensaje por MSN a Reynier Enviar un mensaje por Yahoo  a Reynier
Parte 3

Código PHP:
 // Clase para BDatos MySQL
 
class MySQL{
  var 
$host;     // (string)  Servidor Host donde se haya la BDatos, puede ser el IP o el nombre de dominio
                 // IP : $host = "xxx.xxx.xxx.xxx";
                 // Nombre de Dominio : $host = "www.miservidor.com";
  
var $user;     // (string)  Usuario de conexión a BDatos
  
var $password// (string)  Contraseña de Conexión a BDatos
  
var $db_name;  // (string)  Base de Datos con la cual se trabajará
  
var $port;     // (int)     Puerto por donde será accedida la BDatos

  
function MySQL($host ""$user ""$password ""$db_name ""$port ""){
   
$this->host     = ($host != "")      ?  (string)$host      :  "localhost";
   
$this->user     = ($user != "")      ?  (string)$user      :  "root";
   
$this->password = ($password != "")  ?  (string)$password  :  "";
   
$this->db_name  = ($db_name != "")   ?  (string)$db_name   :  "";
   
$this->port     = ($port != "")      ?  (int)$port         :  3306;
  }

  function 
connect(&$connection$db_name$is_persistent false){
   
$db_name = ($db_name != "")  ?  $db_name  :  $this->db_name;
   if (!
$is_persistent){
    
$connection = @mysql_connect($this->host.':'.$this->port$this->user$this->password);
   }else{
    
$connection = @mysql_pconnect($this->host.':'.$this->port$this->user$this->password);
   }
   if (!
$connection  ||  !@mysql_select_db($db_name$connection)){
    return 
false;
   }
   return 
$connection;
  }

  function 
disconnect(&$connection){
   if (
$connection){
    return @
mysql_close($connection);
   }
   return 
true;
  }

  function 
query($query$connection){
   return @
mysql_query($query$connection);
  }

  function 
numRows($result){
   return @
mysql_num_rows($result);
  }

  function 
affectedRows($result$connection){
   return @
mysql_affected_rows($connection);
  }

  function 
fetchArray($result){
   return @
mysql_fetch_array($result);
  }

  function 
fetchRow($result){
   return @
mysql_fetch_row($result);
  }

  function 
fetchAssoc($result){
   return @
mysql_fetch_assoc($result);
  }

  function 
escape($string){
   return @
mysql_escape_string($string);
  }

  function 
error($connection){
   return 
mysql_error($connection);
  }
 }

 class 
PostGreSQL{
  var 
$host;     // (string)  Servidor Host donde se haya la BDatos, puede ser el IP o el nombre de dominio
                 // IP : $host = "xxx.xxx.xxx.xxx";
                 // Nombre de Dominio : $host = "www.miservidor.com";
  
var $user;     // (string)  Usuario de conexión a BDatos
  
var $password// (string)  Contraseña de Conexión a BDatos
  
var $db_name;  // (string)  Base de Datos con la cual se trabajará
  
var $port;     // (int)     Puerto por donde será accedida la BDatos

  
function PostGreSQL($host ""$user ""$password ""$db_name ""$port ""){
   
$this->host     = ($host != "")      ?  (string)$host      :  "localhost";
   
$this->user     = ($user != "")      ?  (string)$user      :  "root";
   
$this->password = ($password != "")  ?  (string)$password  :  "";
   
$this->db_name  = ($db_name != "")   ?  (string)$db_name   :  "";
   
$this->port     = ($port != "")      ?  (int)$port         :  5432;
  }

  function 
connect(&$connection$db_