0

Usando o Oracle no Debian + classe em PHP5

criado por Roberta Brandão em 21/12/2010 12:52am
Para usar o Oracle no Debian façam o seguinte:

1)Faça o download do oracle-instantclient-foo.rpm do site da oracle.
2)Converta o pacote para Debian: alien oracle-instantclient-foo.rpm

3)Instale o package:
dpkg -i oracle-instantclient-foo.deb

4)Ative o oci8 no php e:

Pronto!

Para conectar no oracle pelo php, pode usar a classe que montei:

ora.class.php:
<?php 
##############################
#                            #
# Oracle Class               #
# Created By Roberta Brandao #
# robertanrbrandao@gmail.com #
##############################

class ora_connect{ 
      var $sid, $connection; 
      var $query; 
      var $host; 
      var $total_record,$rec_position; 
      var $total_fields, $field_name;
	 

        function ora_connect($sid_locale){
				global $ORCL_HOST, $ORCL_USER_NAME, $ORCL_PASSWORD, $SID_VALUE;
				require_once($sid_locale.'/sid.inc');
                $this->host=$ORCL_HOST; 
                $this->sid=$SID_VALUE;
                $this->connection = oci_connect($ORCL_USER_NAME,$ORCL_PASSWORD,$this->sid) or die ($this->get_error_msg($this->connection,"Problem while connecting to ".$this->sid." server..."));
           } 


        function db_query($query_str="") 
       { 
           $this->sql=$query_str; 
           $this->rec_position=0; 
          // if($query_str==""){ 
           //   $query_str=$this->query_stmt; 
           //} 
           $this->query = @oci_parse($this->connection, $query_str); 
           oci_execute($this->query)or die($this->get_error_msg($this->query ,"Query Error : ".$query_str)); 
       } 

       function db_query_return($query_str="",$db=""){ 
           if($query_str==""){ 
              $query_str=$this->query_stmt; 
           } 
           $this->query = oci_parse($this->connection, $query_str); 
            if($db=="Default") { 
                   return oci_execute($this->query,OCI_DEFAULT); 
           } else { 
                   return oci_execute($this->query); 
           } 
       } 

    function select($query_str=""){ 
        $this->sql=$query_str; 
        $this->rec_position=0; 
		@oci_execute(oci_parse($this->connection, "ALTER SESSION SET NLS_DATE_FORMAT = 'DD/MM/YYYY HH24:MI:SS'"));
        $this->query = @oci_parse($this->connection, $query_str); 
        oci_execute($this->query)or die($this->get_error_msg($this->query ,"Query Error : ".$query_str)); 
		while($r = @oci_fetch_array($this->query,OCI_ASSOC+OCI_RETURN_LOBS)){
		$result[] = $r;
		}
		
	return $result;
    }

	function onwhile(){
		while($r = @oci_fetch_array($this->query,OCI_ASSOC+OCI_RETURN_LOBS)){
		$result[] = $r;
		}
	return $result;
	}
    
    function db_fetch_val() 
    { 
        $result=$this->db_fetch_array(0); 
        return $result[0]; 
    } 

    function gen_id($table_name='',$field='',$increment='') { 
         if(empty($increment)) { 
             $increment=1; 
         } else { 
             $increment=$increment; 
         } 
        $sql="select nvl(max($field),0) + $increment from $table_name"; 
        $this->db_query($sql); 
        return $this->db_fetch_val(); 
    } 
      
       function db_fetch_array($fetch_type=0,$db="DEFAULT"){ 
        $result=@oci_fetch_array($this->query,OCI_BOTH+OCI_RETURN_NULLS); 
        
           if(!is_array($result)) 
              return false; 
              $this->total_field=OCINumCols($this->query); 
                     if($db=="DEFAULT"){ 
                           foreach($result as $key=>$val){ 
                                   $result[$key]=trim($val); 
                                   $result[$key]=trim(htmlspecialchars($val)); 
                           } 
                     } 
           return $result; 
       } 



       function get_field_name($i){ 
           return OCIColumnName($this->query, $i+1); 
       } 


       function get_num_fields() { 
           return @oci_num_fields($this->query); 
       } 

       function get_field_type($i, $sql=""){ 
               return oci_field_type($this->query, $i+1); 
       } 
        
       function get_field_size($i, $sql=""){ 
               return oci_field_size($this->query, $i+1); 
       } 
        

       function total_record(){ 
          return oci_num_rows($this->query); 
       } 


       function free(){ 
          @oci_free_statement($this->query); 
          @oci_close($this->connection); 
          unset($this); 
       } 


       function db_fetch_tr ($css="",$colname='y',$add='y',$update='y',$delete='y'){ 
          if($css!=""){ 
              $css_val="class=".$css; 
          } 
          if(!empty($colname)) { 
              echo "<tr $css_val>"; 
              for ($i=0; $i< $this->get_num_fields(); $i++) { 
                   echo "<td>".$this->get_field_name($i)."<td>"; 
              } 
              //echo "<td>Update<td>Delete"; 
              echo "</tr>"; 
          } 
          while($result=$this->db_fetch_array(1)){ 
                    echo "<tr $css_val>"; 
                           for ($j=0; $j<$this->get_num_fields(); $j++) { 
                               $cname=$this->get_field_name($j); 
                                   echo "<td>".$result[$cname]." <td>"; 
                           } 
                    echo "</tr>"; 
          } 

       } 


       function get_error_msg($error_no,$msg=""){ 
          $log_msg=NULL; 
          $error_msg="Custom Error : <pre><font color=red>\n\t".ereg_replace(",",",\n\t",$msg)."</font></pre>"; 
          $error_msg.="System generated Error :"; 
          $error_msg.="<font color=red><pre>"; 
                foreach(oci_error($error_no) as $key=>$val){ 
                        $log_msg.="$key :  ".$val."\n"; 
                        $error_msg.="$key : $val \n"; 
                } 

                $error_msg.="</pre></font>"; 
                return $error_msg; 
       } 

       function get_error_msg_array($error_no){ 
          return oci_error($error_no); 
       } 
} 
?>

Crie uma pasta com o mesmo nome do ORCL_SERVICE_NAME e crie o arquivo abaixo nesta pasta: (com isso você tem a mesma classe mas com conectores distintos, sem precisar configurar os TSNames do Oracle.)
sid.inc:
<?php

##############################
#                            #
# SID Config                 #
# Created By Roberta Brandao #
# robertanrbrandao@gmail.com #
##############################

$ORCL_HOST         = '192.168.10.1';
$ORCL_USER_NAME    = 'root';
$ORCL_PASSWORD     = 'root';
$ORCL_SERVICE_NAME = 'TEST';
$ORCL_PORT         = '1521';
$SID_VALUE = '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST='.$ORCL_HOST.')(PORT='.$ORCL_PORT.')))(CONNECT_DATA=(SERVICE_NAME='.$ORCL_SERVICE_NAME.')))';

?>

functions.class.php:
<?php
##############################
#                            #
# Functions Class            #
# Created By Roberta Brandao #
# robertanrbrandao@gmail.com #
##############################


//start class
class ora_funcs {
	var $conn;

	function ora_funcs($sid){ // inicia uma instancia separada para a funcao
	$this->conn = new ora_connect($sid);
	}

	# search_field(Query, Field_retornado, Tabela, Num de linhas retornado)
	function search_field($query, $field, $table, $rows=0){
	$connfunc = &$this->conn;
	$query = trim($query);
	//$query= addslashes($query);
	$query = "SELECT $field FROM $table where ($query)";
	if($rows!=0){ 
	$query .= " AND ROWNUM <= $rows";
	}
	$connfunc->db_query($query);
	if($connfunc->total_record()>1){ //if num_rows = 0 of the query, return false;
	return $connfunc->onwhile();
	} else {
		return $connfunc->db_fetch_val();
		}

	} //end function search_field


	function close(){
	$connfunc = &$this->conn;
	$connfunc->free();
	}
}
?>

teste.php:
<?php
##############################
#                            #
# Arquivo de Teste           #
# Created By Roberta Brandao #
# robertanrbrandao@gmail.com #
##############################

# declarando classes oracle
include('ora.class.php');
include('functions.class.php');

# instanciando classes
$conn      = new ora_connect('TEST');//carrega classe com o SID TESTE. Note que esta é o nome da pasta onde está o sid.inc.
$ora_funcs = new ora_funcs('CONECTOR2'); //carrega classe de busca avançada. outro sid.inc em outra pasta

$conn  = new ora_connect();
$query = 'select * from tblteste a where a.id not in (10,20,30)'; # <- nao colocar ";" (ponto e virgula) no fim da query.

$result = $conn->select($query);
$conn->free(); //close oracle
unset($conn); //destroi o objeto e libera memoria. (caso necessario)

//print_r($result); // deem uma olhada de como montei o array.

foreach($result as $res){
$ID       = $res['id']; //ou 
$TIPO     = $ora_funcs->search_field("id = '$ID'", 'TIPO', 'CONECTOR2.TABELATESTE2', 1); //envia a query e nao desconecta da instancia
}

$ora_funcs->close(); //fecha a instancia da funcao
unset($ora_funcs);//destroi o objeto e libera memoria. (caso necessario)

?>

Comentários:

Nenhum comentário foi enviado ainda.

Novo Comentário:

(Você pode usar tags como <b>, <i> ou <code>. URLs serão convertidas para links automaticamente.)