Undefined variable error occurs when using classes

Asked

Viewed 642 times

-3

I’m making a connection with Firebird through a PHP class, using PDO, however it is occurring a very sinister error in which I got lost, watch the pages, index.php / connect.php and class.

INDEX.PHP

require("conectar.php");   
$sql = "SELECT NOMCLI FROM SINAF019";
$stmt = $lokos->query($sql);
$stmt->execute();
$itens = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($itens !== false)
    {  foreach($itens as $row) {
            echo  "<span>".$row['NOMCLI']."</span>";
        }
    }

Connect.php

require("conectarDuosig.class.php");
$duo = new Duosig();
$duo->host = "127.0.0.1";
$duo->user = "SYSDBA";
$duo->pass = "masterkey";
$duo->dbnome = "127.0.0.1:DCOL";
$duo->conecta();

conectarDuosig.class.php

class Duosig{
         // variaveis para a conexão
     public $host;
     public $user;
     public $pass;
     public $dbnome;
         // função para conectar
     function conecta(){
          $lokos=new PDO("firebird:localhost=$this->host;dbname=$this->dbnome",$this->user, $this->pass);
     }
}

When I do with the class it error on line 21 which in case is the

  $stmt = $lokos->query($sql);

But when I make the connection pure, right into the source code

going there and putting

$lokos=new PDO("firebird:localhost=127.0.0.1;dbname=127.0.0.1:DCOL", $pass, $user);

and do the select, it pulls normal.

  • Could inform the error that occurs?

  • 2

    I noticed that you have several answers that solved your problem, but you did not mark any as "correct", I suggest you take the tour to understand how the site works http://answall.com/tour . The community thanks you.

  • 2
  • 1

    Please @Edwardjunior, register here: http://meta.pt.stackoverflow.com/q/4067/132

3 answers

7

The problem is that $lokos is a private variable of conecta() that is not accessible outside the method, to pick up the connection the simplest way would be to just add return in conectar().

function conecta(){
   return new PDO(...);
}

In INDEX.php

require("conectar.php");   

$lokos = $duo->conecta();

$sql = "SELECT NOMCLI FROM SINAF019";
$stmt = $lokos->query($sql);
$stmt->execute();
$itens = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($itens !== false)
    {  foreach($itens as $row) {
            echo  "<span>".$row['NOMCLI']."</span>";
        }
    }

1

You have ignored the Object’s inheritance rules in this case, as you can only call a PDO method through your class only after it is instantiated within it. Also check the private and public methods of the PDO object you are calling.

Try it like this:


<?php

class ConexaoDatabase
{

 private static $servidor = '127.0.0.1'; // Servidor, no caso poderia ser também localhost
 private static $usuario = 'SYSDBA'; // usuário do banco de dados
 private static $senha = 'masterkey'; // senha do banco de dados
 private static $banco = '127.0.0.1:DCOL'; // nome do banco de dados
 private static $instance = null;

 public static function getConnection()
 {
     if (!self::$instance instanceof PDO) {
        try {
             self::$instance = new PDO('firebird:localhost=' . 
             self::$servidor . ';dbname=' . 
             self::$banco, 
             self::$usuario, 
             self::$senha, 
             array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        } catch (PDOException $exc) {
            echo "Erro ao conectar :: {$exc->getMessage()}";
        }
     }
 return self::$instance;
 }

 public function fetchAll($query)
 {
    $con = self::getConnection();
    $stmt = $con->prepare($query);
    $this->execute($stmt);

    if ($stmt->rowCount()) {
       return $stmt->fetchAll(PDO::FETCH_OBJ);
    } else {
      return false;
    }
 }

 public function fetch($query)
 {
    $con = self::getConnection();
    $stmt = $con->prepare($query);
    $this->execute($stmt);

    if ($stmt->rowCount()) {
       return $stmt->fetch(PDO::FETCH_OBJ);
    } else {
      return false;
    }
 }

 public function execute(PDOStatement $stmt, array $data = null)
 {
    try {
          if (isset($data)) {
             $stmt->execute($data);
          } else {
            $stmt->execute();
          }
        } catch (PDOException $exc) {
          echo $exc->getTraceAsString();
          var_dump($exc->getMessage());
    }
 }

 /** 
  UPDATE OR INSERT DATA
 **/
 public function save($sql, array $data)
 {
    $con = self::getConnection();
    $stmt = $con->prepare($sql);
    $this->execute($stmt, $data);
    if ($stmt->rowCount()) {
       return true;
    } else {
      return false;
    }
 }

}

?>

To call the method:


$conexao = new ConexaoDatabase();
$sql = "SELECT NOMCLI FROM SINAF019";
$itens = $conexao->fetchAll($sql);
if ($itens !== false) {
    foreach ($itens as $row) {
      echo "<span>".$row->NOMCLI."</span>\n";
    }
}

-13

all I had to do was give only the code itself

public function conecta()
{ 
    $lokos = new PDO("firebird:localhost=$this->host;dbname=$this->dbnome", 
                     $this->user, $this->pass); 
    return $lokos; 
} 

and then call you normally

Browser other questions tagged

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