Error when connecting database with PDO

Asked

Viewed 1,061 times

2

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

Notice: Undefined variable: Operator in C: xampp htdocs cadastroDelunos app.ado Tcriteria.class.php on line 16

Notice: Undefined variable: Conn in C: xampp htdocs cadastroDelunos app.ado Tconnection.class.php on line 46

Fatal error: Call to a Member Function setAttribute() on a non-object in C: xampp htdocs cadastroDelunos 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;
    }
}
?>
  • A var_dump of the variable $db in the method TConnection::open returns what? Your file ini looks badly formatted (I don’t know if PHP accepts in the way you wrote).

  • Both Connection.ini and php.ini are configured

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

4

The errors are self-explanatory.

The first is typo. Just switch to line 16:

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

The second is that the variable does not exist because it did not enter any case. You have to treat this situation because it may 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');

I put in the Github for future reference.

But I’d still have to fix the configuration on ini.

The third error is the consequence of the second.

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

Although it will not cause problem most times p ideal is not to use file_exists. Let the error happen while accessing the file, if any, even generate the exception you want. Even if it is a bad idea to generate an exception in this way. But I won’t go into details because it’s not the focus of the question.

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

host = "127.0.0.1"
name = "sistema_escolar"
user = "root"
pass = "senha aqui"
type = "mysql"

Browser other questions tagged

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