The undefined variable error occurs when I use classes

-3

I am making a firebird connection through a PHP class, using the PDO, however it is experiencing a pretty sinister error in which I got lost, look at the pages, index.php / connect.php and the 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();

connectDuosig.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's the error on line 21 which in the case is the

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

But when I make the connection pure, direct in the source code

Going and Laying

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

and I do the select, it pulls normal.

    
asked by anonymous 02.07.2015 / 16:01

3 answers

7

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

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

No 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>";
        }
    }
    
02.07.2015 / 17:50
1

You have ignored Object inheritance rules in this case since you can only invoke an 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 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";
    }
}

    
02.07.2015 / 19:20
-12

I just gave the return of 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 it normally

    
02.07.2015 / 21:20