How to Connect to Database by Reading INI File (Function and Class)

Asked

Viewed 592 times

0

How can I connect to the database (PHP in 3 Layers [Facade / Repository / Database]) by reading the information from a file. ini and assigning these values in a function within a class ?

Banco.php

class Banco {
  var $server;
  var $bd;
  var $user;
  var $password;
  var $erro;
  var $result;
  var $conexao;

  function Banco ($user="usuario",$pass="senha",$db="banco",$srv="servidor") {
    if(!$this -> SetConexao($srv,$user,$pass)) {
      $this -> SetErro("Erro de Conexão - ".mssql_get_last_message($this -> GetConexao()));
      mssql_close();
      return false;
    }
    if(!$this -> SetBd($db)) {
      $this -> SetErro("Banco não Encontrado - ".mssql_get_last_message($this -> GetConexao()));
      mssql_close();
      return false;
    }
  }
.......... mais código .........
}

Arquivo . INI

[BANCO]
user = usuario
pass = senha
db = banco
srv = servidor

Reading File . INI

$ini = parse_ini_file('config.ini', true);
$cUser = $ini['BANCO']['user'];
$cPass = $ini['BANCO']['pass'];
$cDb = $ini['BANCO']['db'];
$cSrv = $ini['BANCO']['srv'];

Class .... {

blabla.....

function Banco ($user=$cUser,$pass=$cPass,$db=$cDb,$srv=$cSrv) { <-- Erro ao conectar ao banco

Would anyone have any idea how I could make this kind of connection without having to undo the layers of connection in php ?

1 answer

1


You are mixing the class definition with the object instantiation. You do not pass the = so directly. You need to do something this way:

<?php

// Aqui vem a definação da classe
class Banco { 
// ...
}

// Aqui a instanciação
$ini = parse_ini_file('config.ini', true);
$cUser = $ini['BANCO']['user'];
$cPass = $ini['BANCO']['pass'];
$cDb = $ini['BANCO']['db'];
$cSrv = $ini['BANCO']['srv'];


$db = new Banco();
$db->Banco($cUser, $cPass, $cDb, $cSrv);
  • I had done so, but I was reading the ini outside the function of the bank instance, it was lack of attention even. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.