I can’t display DB data in front-End

Asked

Viewed 103 times

-1

Hello, I need your help because I’m stuck in the following scenario: I created a system where the user can register a link and the name of a site, until then everything was quiet, then soon after I tried to make a system to display what was registered in DB, in html, only I can not at all, if someone can give me a strength, thanks.

So far I was able to pull the database data using foreach and display with an echo, only I could not put it in html.

This is the connection class I created, and it has the methods of registering and retrieving the database data. And below the class has the html code

<?php

class Conexao {

    # Variável que guarda a conexão PDO.
    private $db;
    private $resultado;

    public function __construct() {

    $db_host = 'localhost';
    $db_name = 'links';
    $db_pass = '';
    $db_user = 'root';

    try
        {
            # Atribui o objeto PDO à variável $db.
            $this->db = new PDO("mysql:host=$db_host; dbname=$db_name", $db_user, $db_pass);
            # Garante que o PDO lance exceções durante erros.
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            # Garante que os dados sejam armazenados com codificação UFT-8.
            $this->db->exec('SET NAMES utf8');
        }
        catch (PDOException $e)
        {
            # Então não carrega nada mais da página.
            die("Connection Error: " . $e->getMessage());
        }
    }

    public function cadastrar() {
        if(isset($_POST['enviar'])){
            $nome = $_POST['nome'];
            $link = $_POST['link'];
            $sql = $this->db->prepare('INSERT INTO links (nome, link) VALUES (?, ?)');
            $sql->execute(array($nome, $link));
            header('Location: ../../Public/index.php');
            die();
        }
    }

    public function recuperar() {
        $sql = $this->db->prepare('SELECT nome, link FROM links');
        $sql->execute();

        $this->resultado = $sql->fetchAll(PDO::FETCH_ASSOC);
        foreach($this->resultado as $key => $resulta) {
            echo $this->resultado[$key]['nome'] .' - '. $key;
        }
    }
}

$cadastro = new Conexao();
$cadastro->cadastrar();```

File with HTML

<?php
require_once '../App/Classes/Connect.class.php';
$teste = new Conexao();
$teste->recuperar();
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Links</title>
    <link rel="stylesheet" href="Css/Estilo.css">
    <link rel="stylesheet" href="Bootstrap/Css/bootstrap.min.css">
    <link rel="stylesheet" href="Fontawesome/css/all.min.css">
</head>
<body>


<nav id="nav-alinhar" class="navbar navbar-expand-lg navbar-light bg-secondary">
  <a class="navbar-brand text-light text-navbar" href="index.php">M</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
</nav>

<section><!-- Área de cadastrar links -->
  <div class="row">
    <div class="col-md-4 bg-light">
      <ul>
        <hr>
        <li>
          <a href="index.php" class="lateral">Cadastrar/Remover Links</a>
        </li>
        <hr>
        <li>
          <a href="ListarLinks.php" class="lateral">Mostrar todos os links</a>
        </li>
        <hr>
      </ul>
    </div>

    <div class="col-md-8">
        <div class="mt-2">
            <div class="mb-4">
                <input type="text" class="mod-buscar" placeholder="Ex: Coelba"> <i class="fas fa-search"></i>
            </div>
            <p></p>
          </div>
    </div>

  </div><!-- /row -->
</section><!-- /Área de cadastrar links -->
    

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>

1 answer

0

Its function recuperar should return the values consulted, for example:

public function recuperar() {
        $sql = $this->db->prepare('SELECT nome, link FROM links');
        $sql->execute();

        $this->resultado = $sql->fetchAll(PDO::FETCH_ASSOC);
        
        return $this->resultado;
    }

Then you can use the method to receive the result and list it in HTML, for example within a PHP page with HTML mounting a table:


<table>
<?php     
   $teste = new Conexao();

   $resultados = $teste->recuperar();

   foreach($resultados as $key => $res) {
?>
   <tr>
      <td><?php echo $res[$key]['nome']; ?></td>
      <td><?php echo $key; ?> </td>
   </tr>
<?php
   }
?>
</table

I suggest studying the theory of Object-Oriented Programming to help you with the basics for programming in any language:

Browser other questions tagged

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