PHP OO Problems with Classes

Asked

Viewed 586 times

1

Good evening, I am trying to implement a method that registers the user comment in the database in the comment table that has the foreign key id_usuario. How do I get access to this id_usuario? I tried using my getIdUsuario method of the User class, but it returns null. When the user logs in to the system I am passing all the select information by the set() functions and even then it returns null.

<? php
require_once("classes/Conexao.class.php");

class UsuarioDAO {
  function __construct() {
    /
			$this->con = new Conexao(); 
			$this->pdo = $this->con->Connect(); /
  }

  public
  function existeUsuario($email) {

      $query = $this - > pdo - > prepare("SELECT * FROM 'usuario' WHERE  email = '$email'");
      var_dump($query);
      $query - > execute();

      if ($query - > rowCount() >= 1) {
        return true;
      } else {
        return false;
      }

    } //fecha metodo existe

  public
  function logar($usuario) {
    try {
      $query = $this - > pdo - > prepare("SELECT * FROM usuario WHERE  email = :email AND senha = :senha");

      $param = array(
        ":email" => $usuario - > getEmail(),
        ":senha" => $usuario - > getSenha()
      );
      $query - > execute($param);
      if ($query - > rowCount() >= 1) {
        while ($row = $query - > fetch(PDO::FETCH_ASSOC)) {
          $usuario - > setNome($row['nome']);
          $usuario - > setEmail($row['email']);
          $usuario - > setSenha($row['senha']);
          $usuario - > setIdUsuario($row['id_usuario']);

        }
        $usuario_id = $usuario - > getIdUsuario();

        return $usuario; //executa a sql com os parametros 
      }

    } catch (PDOException $ex) { //caso haja erro
      echo "ERRO:" + $ex - > getMessage(); //exibe o erro
    }
  }

  public
  function cadastrar($usuario) {
      try {
        $param = array(
          ":nome" => $usuario - > getNome(),
          ":email" => $usuario - > getEmail(),
          ":senha" => $usuario - > getSenha()
        );

        $email = $usuario - > getEmail();

        if ($this - > existeUsuario($email)) { //se existir usuario com esse email
          echo "Usuário ja cadastrado!";
          return false;
        } else {
          $query = $this - > pdo - > prepare("INSERT INTO usuario(nome, email, senha) 
                                        VALUES (:nome, :email, :senha)");
          $query - > execute($param); //executa a sql com os parametros 			
          return true;

        }

      } catch (PDOException $ex) {
        echo "ERRO:" + $ex - > getMessage();
      }
    } //fecha a funcao

} //fecha classe
?>
<?php

require_once("/classes/Conexao.class.php"); //Incluimos o arquivo de conexão.
require_once("classes/entidade/Usuario.class.php");
require_once("classes/dao/UsuarioDAO.class.php");
class comentarioDAO { //Criamos uma classe chamada cometarioDAO

function __construct() { //Método contruct inicia automáricamente quando a classe é instanciada.
    $this->con = new Conexao(); //Propriedade con instancia nossa classe de conexao.
    $this->pdo = $this->con->Connect(); //Propriedade con acessa o método Connect que esta dentro da classe conexao.
}

public function cadatrarComentario(comentario $entComentario) {//Criamos um método que será responsável por gravar os comentários, como parâmetro ele recebe nossa entidade comentário. 
    try { //Executa nosso código
        ////pagina, nome, e-mail, comentário, data, hora, ip e status
        $usuario = new Usuario();
        $usuarioDAO = new UsuarioDAO();
        $usuarioDAO->logar($usuario);
        $email = $usuario->getEmail();

        print_r($usuario);
 
        $query1 = $this->pdo->prepare("SELECT id_usuario FROM usuario WHERE email = $email");

        $resultId = $query1->execute(array(':email'=>email));


        while ($row = $resultId->fetch(PDO::FETCH_ASSOC)) {
                    $usuario->setIdUsuario($row['id_usuario']);
            
        }
        $stmt = $this->pdo->prepare("INSERT INTO comentario (comentario, data, hora, id_usuario) 
                                    VALUES ( :comentario, :data, :hora, :idUsuario)");

        $param = array(//Criamos um array associativo, onde temos :nome será trocado pelo valor vindo do nosso método get da entidade, estes dados erão tratados apra evitar probleamas
            ":comentario" => $entComentario->getComentario(),
            ":data" => date("Y/m/d"),
            ":hora" => date("h:i:s"),
            ":idUsuario" => $usuario->getIdUsuario()
        );
        
        return $stmt->execute($param); // Aqui executamos nosso SQL e passamos os parâmetros, o reusltado é retornado no nosso método

    } catch (PDOException $ex) { //Se houver algum erro no nosso código vamos criar uma exceção para informar onde esta o erro.
        echo "ERRO: " + $ex->getMessage(); //Exibimos a mensagem de erro e pegamos o código do erro.
    }
}

//Método de consulta

public function consultarComentario($pagina) {
    try { //Executa nosso código
        $stmt = $this->pdo->prepare("SELECT * FROM comentarios WHERE cm_pagina = :pagina AND cm_status = 1");
        
        $param = array(":pagina" => $pagina);//Neste caso não precisamos chamar a entidade, é mais trabalhoso e apenas vamos passar um valor como parâmetro.
        
        $stmt->execute($param); //Passamos o parâmetro para a execução.
        
       return $stmt->fetchall(PDO::FETCH_ASSOC); //Resumindo aqui retornamos todos os dados da nossa consulta,se quer retornar só um use apenas fetch e não fetchall
        
    } catch (PDOException $ex) { //Se houver algum erro no nosso código vamos criar uma exceção para informar onde esta o erro.
        echo "ERRO: " + $ex->getMessage(); //Exibimos a mensagem de erro e pegamos o código do erro.
    }
}

}

?>

<?php
	class Usuario {
		
		protected $idUsuario;
		protected $nome;
		protected $email;
		protected $senha;
		protected $foto; 

		public function getIdUsuario(){
			return $this->idUsuario;
		}
		public function setIdUsuario($idUsuario){
			$this->idUsuario = $idUsuario;
		}
		public function getNome(){
			return $this->nome;
		}
		public function setNome($nome){
			 $this->nome = $nome;
		}

		public function getEmail(){
			return $this->email;
		}
		public function setEmail($email){
			$this->email = $email;
		}

		public function getSenha(){
			return $this->senha;
		}
		public function setSenha($senha){
			$this->senha = $senha;
		}

		public function getFoto(){
			return $this->foto;
		}
		public function setFoto($foto){
			$this->foto = $foto;
		}


		
		

	}//fecha a classe
?>

I can’t access the idUsuario between classes

  • I fixed the query and tbm the call of the log method that asks for an object as parameter like this: $usuarioDAO->login($usuario); But in getEmail var_dump it comes null

  • In the log method return the object $usuario and not true.

  • Still not accessing attributes of the User class

  • Is it encapsulation? Because the attributes are protected and my Comment class is in another folder.

  • As this is the visibility of user class attributes?

  • Do the right Prepared in email: $query1 = $this->pdo->prepare("SELECT id_usuario FROM usuario WHERE email = :email"); $resultId = $query1->execute(array(':email' => $email));

  • Need tbm of a fetch on ($resultId) to pick up the result and pass the Insert.

  • I didn’t understand how to use fetch

  • It worked out the Insert?

  • No, the problem is in $email that is not captured in getEmail, I don’t know how to access this attribute, it seems that when I prompt the User class creates a new user with empty attributes.

  • About instantiating the class, it is the basis of Object Orientation, whenever you instantiate the class it will create a new object, with all attributes zeroed. When it gives a "new user();" you need to "popular" it with data. Your biggest problem apparently is to make this data, the user, get there. What is the program flow, before arriving at the function cadastrarComentario? (Which, by the way, is missing an s in the definition. ;D)

  • You probably need to save (or search) who this user is by the session, or by cookies or something, for you to "know" who is logged in, commenting on the system. In the case of PHP it is worth looking at how $_SESSION works.

  • How could I apply Ssion between classes?

Show 8 more comments

1 answer

4


Your user will always come back empty, by registering comment you are creating a new (empty) User instance and sending to the method $usuarioDAO->logar($usuario);. You are not sending any parameter to your query, so it will not find anything and your method will always return the empty User object you previously submitted.

Your confusion is in the variable $usuario, when you log in and arrow the values in the object using the public methods below:

$usuario - > setNome($row['nome']);
$usuario - > setEmail($row['email']);
$usuario - > setSenha($row['senha']);
$usuario - > setIdUsuario($row['id_usuario']);

You filled in your object, okay! But the variables in php are volatile, that is, they only exist while a script is running, when moving from one page to another they cease to exist (unless of course they are transferred to the next [get or post] page, or set to global).

By instantiating the object again Usuario in the method cadatrarComentario() that you created, you are NOT calling that user who logged in earlier, because that object "died" from the moment your script finished running. In reality there you are creating a new object in memory EMPTY, with nothing!

The recommended ai would be to use session in php, a basic example in this case would be:

1 - Sign in first of all in your php file you will use:

<?php
    session_start();
    // seu código abaixo
?>

2 - When logging in the user store his or her id or other information you will need (basic, without compromising the integrity of the same and its database) not to perform a new query in the database each time you need:

public function logar($usuario) {
    try {
        $query = $this - > pdo - > prepare("SELECT * FROM usuario WHERE  email = :email AND senha = :senha");
        $param = array(
            ":email" => $usuario - > getEmail(),
            ":senha" => $usuario - > getSenha()
        );
        $query - > execute($param);
        if ($query - > rowCount() >= 1) {
            while ($row = $query - > fetch(PDO::FETCH_ASSOC)) {

               // GUARDANDO NA SESSÃO AO INVÉS DE DO OBJETO
                $_SESSION['ID_USER'] = $row['id_usuario'];


        // Continuação do seu código...

When registering the comment, log in at the beginning of the php file (in this case ComentarioDAO.class.php) as in step 1 and when you need the user id call the variable you created in the session so:

$stmt = $this->pdo->prepare("INSERT INTO comentario (comentario, data, hora, id_usuario) VALUES ( :comentario, :data, :hora, :idUsuario)");

$param = array(//Criamos um array associativo, onde temos :nome será trocado pelo valor vindo do nosso método get da entidade, estes dados erão tratados apra evitar probleamas
    ":comentario" => $entComentario->getComentario(),
    ":data" => date("Y/m/d"),
    ":hora" => date("h:i:s"),
    ":idUsuario" => $_SESSION['ID_USER'] // Chamando aqui o valor que armazenou
);

You can store the values you need by creating the names you want ($_SESSION['NOME_USER'], $_SESSION['NOME']...).

Remembering that it is a simple example, try to read better on the subject, there are other issues such as the security of all this.

I hope this brief explanation helps you.

Hugs

  • Thank you so much @Mastria

Browser other questions tagged

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