Error connecting database with PDO

2

I have an OOP code in PHP, when I try to connect to the DB, the following error appears:

  

Notice: Undefined variable: operator in C: \ xampp \ htdocs \ StudentCount \ app.ado \ TCriteria.class.php on line 16

     

Notice: Undefined variable: conn in C: \ xampp \ htdocs \ StudentContext \ app.ado \ TConnection.class.php on line 46

     

Fatal error: Call to a member function setAttribute () on a non-object in C: \ xampp \ htdocs \ StudentContext \ app.ado \ TConnection.class.php on line 46

conection.ini

host = ['127.0.0.1']
name = ['sistema_escolar']
user = ['root']
pass = ['']
type = ['mysql']

connection.php

<?php
function __autoload($classe)
{
    if(file_exists("../app.ado/{$classe}.class.php"))
    {
        include_once "../app.ado/{$classe}.class.php";
    }
}

$sql = new TSqlSelect;

$sql->setEntity('sistema_escolar');

$sql->addColumn('id');
$sql->addColumn('nome');

$criteria = new TCriteria;

$criteria->add(new TFilter('id','=','1'));

$sql->setCriteria($criteria);

try
{
    $conn = TConnection::open('connection');

    $result = $conn->query($sql->getInstruction()); 
    if($result)
    {
        $row = $result->fetch(PDO::FETCH_ASSOC);
        echo $row['id'].'-'.$row['nome']."\n";
    }
    $conn = null;
}
catch(PDOException $e)
{
    print "Erro: ".$e->getMessage()."<br/>";

}
?>

TCriteria.class.php

<?php
class TCriteria extends TExpression
{
    private $expressions;
    private $operators;
    private $properties;

    public function add(TExpression $expression, $operator = self::AND_OPERATOR)
    {
        if(empty($this->expressions))
        {
            unset($operator);
        }

        $this->expressions[] = $expression;
        $this->operators[] = $operator;
    }

    public function dump()
    {
        if(is_array($this->expressions))
        {
            foreach($this->expressions as $i => $expression)
            {
                $operator = $this->operators[$i];
                $result .= $operator . $expression->dump() . ' ';
            }
            $result = trim($result);
            return "({$result})";
        }
    }

    public function setProperty($property, $value)
    {
        $this->properties[$property] = $value;
    }

    public function getProperty($property)
    {
        return $this->properties[$property];
    }
}
?>

TConnection.class.php

<?php
final class TConnection
{ 
    private function __construct()
    {

    }

    public static function open($name)
    {
        if(file_exists("../app.config/{$name}.ini"))
        {
            $db = parse_ini_file("../app.config/{$name}.ini");
        }

        else 
        {
            throw new Exception("Arquivo '$name' não encontrado");
        }

        $user = $db['user'];
        $pass = $db['pass'];
        $name = $db['name'];
        $host = $db['host'];
        $type = $db['type'];

        switch($type)
        {
            case 'pgsql':
                $conn = new PDO("pgsql:dbname={$name};user={$user};password={$pass};host={$host}");
                break;

            case 'mysql':
                $conn = new PDO("mysql:host=".$host.";dbname={$name}",$user,$pass);
                break;

            case 'ibase':
                $conn = new PDO("firebird:dbname={$name}",$user,$pass);
                break;

            case 'mssql':
                $conn = new PDO("mssql:host={$host},1433;dbname={$name}",$user,$pass);
                break;      
        }

        $conn->setAttribute(PDO::ATTR_MODE, PDO::ERRMODE_EXCEPTION);

        return $conn;
    }
}
?>
    
asked by anonymous 05.09.2015 / 18:16

1 answer

4

Errors are self-explanatory.

The first is a typo. Just switch on line 16 to:

    $this->operators[] = $operators; //faltava um s aqui

The second is that the variable does not exist because it has not entered any case . You have to address this situation because it can exist. And probably your configuration is wrong because you did not specify any type. So I would put this at the end of switch :

default:
    throw new PDOException('Nenhum tipo de banco de dados foi selecionado');

But you would still have to sort the setting in ini .

The third error is a consequence of the second.

Actually it has a better solution but it would have to change its application a lot.

Although it will not be a problem most of the time, it is ideal to not use file_exists . Let the error happen when accessing the file, if any, until you generate the exception you want. Even though it is a bad idea to generate an exception this way. But I will not go into details because it is not the focus of the question.

Temporarily print the value of the variables $user , $pass , $name , $host and $type . You will see that they are worthless or have wrong values. Then you have problems with your ini . In fact the way it is written is wrong the most likely would be:

host = "127.0.0.1"
name = "sistema_escolar"
user = "root"
pass = "senha aqui"
type = "mysql"
    
05.09.2015 / 18:32