How to return a query column within a class

Asked

Viewed 86 times

0

I’m updating my entire project to object-oriented PDO, but I’m having some difficulty returning a fetch column in the class query User. After several attempts, so was my code:

user php.

Class User {

    public $usr_idLogged = 1;

    public function selectUser() {

        try {

            $classConnection = new Connection();
            $openConn = $classConnection->openConn();

            $stmt = $openConn->prepare('SELECT * FROM tbl_users a JOIN tbl_users_picture b ON a.usr_id = b.usrPic_idUser WHERE usr_id = :usr_id;');
            $stmt->bindParam(':usr_id', $usr_idLogged);
            $stmt->execute();
            $usr_idLogged_f = $stmt->fetch();
        }
        catch (PDOException $e) {
            echo "There is some problem in connection: " . $e->getMessage();
        }
    }   
}

And here’s the page where I want to display one result at a time.

panel.php

              $classUser = new User();
              $classUser->selectUser();


              if ((!empty($classUser->usr_idLogged_f['usrPic_path'])) && (file_exists($classUser->usr_idLogged_f['usrPic_path']))) {
                  echo '<img class="image--profile" src="'.$classUser->usr_idLogged_f['usrPic_path'].'" title="Open your profile">';
              }
              else {
                echo '<img class="image--profile" src="images/user_m.png">';
              }

In case I want to display the column of fetch I gave, but I always end up in a different error related to the variable, in case usr_idLogged_f['usrPic_path']).

1 answer

1

There are some ways you can solve this problem. You can declare your method as static and so instantiate the direct obejto. (I haven’t circled your code, so my tip goes in the dark)

Below is the mentioned:

<?php
class User {

    public $usr_idLogged = 1;

    public static function selectUser() {

        try {
            $classConnection = new Connection();
            $openConn = $classConnection->openConn();

            $stmt = $openConn->prepare('SELECT * FROM tbl_users a JOIN tbl_users_picture b ON a.usr_id = b.usrPic_idUser WHERE usr_id = :usr_id;');
            $stmt->bindParam(':usr_id', $usr_idLogged);
            $stmt->execute();
            $usr_idLogged_f = $stmt->fetch();
        }
        catch (PDOException $e) {
            echo "There is some problem in connection: " . $e->getMessage();
        }
      }
     }
    ?>

However, as you are doing in PDO, it is ideal that you do the Getters and Setter, and then create the methods and create a connection class. As I don’t know how your connection is being made, I will send an example and how would the two files.

Class Connexion

<?php
class Connection extends PDO{
    private $conn;
    //Conexão automática ao banco de dados
    public function __construct()
    {
        $this->conn = new PDO("mysql:host=localhost;dbname=dbphp7", "root","");//Pode ser passado por paramêtros com bindParam caso exista mais de um servidor
    }
    //Associação de parâmetros passados
    private function setParams($statment, $parameters = array()){
        //Com este foreach, é possível passar quantos parâmetros necessários
        foreach ($parameters as $key => $value) {
            //O $this->setParam está chamando o método abaixo, no qual executa o bind de apenas um parâmetro, porém, devido ao foreach, este bind será executado quantas vezes for necessário
            $this->setParam($statment, $key, $value);
        }
    }
    //Ao contrário do método setParams, este executa o bind de apenas um parâmetros, por isso o nome Param, pois é apenas um
    private function setParam($statment, $key, $value){
        $statment->bindParam($key, $value);
    }
    //Execução de um comando ao banco
    public function query($rawQuery/*Query bruta que será tratada depois*/, $param = array())
    {
        //Comando de execução no banco
        $stmt = $this->conn->prepare($rawQuery);
        //Chamando o métododo setParams e associando os parâmetros statement = $stmt e parameter = $param.
        //A variável $stmt está chamando o comando de execução no banco.
        //A variável $param está recebendo o array
        //Cada variável passada refere-se a exigência do método setParams
        $this->setParams($stmt, $param);
        //Executando
        $stmt->execute();
        //Retornando a execução
        return $stmt;
    }
    //Método para o select
    public function select($rawQuery, $params = array()):array{
        //O $stmt é o que o método quey retorna
        $stmt = $this->query($rawQuery, $params);
        //Retorna o fetchAll com os dados associativos
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

Class of methods

<?php
class User {

    public $usrPic_path;

    public function setUsrPic_path($usrPic_path){
        $this->usrPic_path = $usrPic_path;
    }
    public function getUsrPic_path($usrPic_path){
        return $this->usrPic_path;
    }

    public function setData($data){
        //Envia os dados, por vetor e row, para os métodos setters
        $this->UsrPic_path($data["usrPic_path"]);
    }

    public function selectUser() {
        $openConn = new Connection();
        $resultado = $openConn->prepare('SELECT * FROM tbl_users a JOIN tbl_users_picture b ON a.usr_id = b.usrPic_idUser WHERE usr_id = :usr_id;', array(
            ':usr_id'=>$usrPic_path
        ));
        if(count($resultado)>0){
            $this->setData($resultado[0]);
        }
    }   
}
?>

Autoload of the connection in the classes

<?php
//Auto load das classes
spl_autoload_register(function($class_name){
    //Passa o nome do arquivo
    $filename = "class". DIRECTORY_SEPARATOR .$class_name.".php";
    //Se este arquivo existir, ele é invocado
    if (file_exists(($filename))){
        require_once($filename);
    }
});
?>

Index

<?php
    include('user.php');

    $classUser = new User();
    $classUser_select = $classUser->usr_idLogged;

    if ((!empty($classUser_select)) && (file_exists($classUser_select))) {
        echo '<img class="image--profile" src="'.$classUser_select.'" title="Open your profile">';
    }
    else {
    echo '<img class="image--profile" src="images/user_m.png">';
    }
?>

I hope I’ve helped.

Browser other questions tagged

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