PDO Error - Call to a member functio on null

0

I created a function to make a query in the DB and return a User from the variable $nome passed by parameter, however, when testing it it enters the else, would anyone know where the error is?

Note: The PDO connection is working and there is a user with the test name inside the DB.

Function:

public static function obtemUsuarioPorNome($db,$nome){
        $stmt = $db->prepare("SELECT id,nome,senha FROM usuarios WHERE nome = :nome");
        $stmt->bindParam(":nome", $nome);
        $stmt->execute();
        if($row = $stmt->fetch(PDO::FETCH_ASSOC) == $nome){
            extract($row);
            $usuario = new Usuario($id,$nome,$senha);
            return $usuario;
        } else {
            return null;
        }
    }

Test code:

$objUsuario = Usuario::obtemUsuarioPorNome($dblink,"barba-ruiva");
print("<p>".$objUsuario->getNome()." ".$objUsuario->getId()."</p>");
    
asked by anonymous 09.09.2018 / 02:21

1 answer

0

You can not compare the NAME with the FETCH_ASSOC result, because it returns to the ROW variable, an associative array containing the SELECT response data.

public static function obtemUsuarioPorNome($db,$nome) {
   $stmt = $db->prepare("SELECT id,nome,senha FROM usuarios WHERE nome = :nome");
   $stmt->bindParam(":nome", $nome);
   $stmt->execute();
   $row = $stmt->fetch(PDO::FETCH_ASSOC);
   if(count($row) > 0) {
      // extract($row);
      $usuario = new Usuario($row["id"], $row["nome"], $row["senha"]);
      return $usuario;
   } else {
      return null;
   }
}
    
22.09.2018 / 19:37