Mysql connection within a class

Asked

Viewed 37 times

-1

Hello, I’m having a hard time making a connection to the database. To make the connection I created a class called Conexao and I am using PDO, when I need to make a select, for example, I call the connection class within the class Credenciais that has the method PegaCredenciais, where the select will be made.

When I perform the class instance Credenciais inside the archive Classes/Credentials.php, where it is, it works perfectly. But when the instance is done in the file index php., i get error 500 when loading the page and only solves the error when I withdraw the class Conexao from within the method PegaCredenciais.

I have already done tests and the selection class is visible in the file index php., I’m using the Composer.

index php.

require __DIR__.'/vendor/autoload.php';
use \Classes\Credenciais;

$credenciais = new Credenciais();
$credenciais->PegaCredenciais();

Classes/Credentials.php

namespace Classes;
    
class Conexao{
     private static function connect(){
        return new PDO("mysql:host=localhost;dbname=meu_banco", "meu_banco", "root");
     }
}

class Credenciais{
    public function PegaCredenciais(){
        $db = Conexao::connect();
        $dados = $db->query("SELECT * FROM credenciais WHERE id = '1'");
        $dados = $dados->fetch(PDO::FETCH_OBJ);
        return $dados->token;
    }
}

Composer.json

"autoload":{
    "psr-4":{
         "Classes\\":"Classes/"
    }
}

1 answer

0

I was able to solve the problem. The PDO class was not being located, to use namespace I need to insert a slider backwards before setting PDO.

Ex:

$dados->fetch(\PDO::FETCH_OBJ);

Browser other questions tagged

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