Advertisement
luistavares

PHP - Página PHP para realizar pesquisa (filtro) em banco de dados

Mar 15th, 2023
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | Source Code | 0 0
  1. <html lang="pt-br">
  2.     <head>
  3.         <meta charset="utf-8">
  4.         <title>Agenda</title>
  5.     </head>
  6.     <body>
  7.         <h2>Pesquisa de Contatos</h2>
  8.         <form method="post" action="pesquisa.php">
  9.             <label>Nome parcial:</label>
  10.             <input type="text" name="nome" />
  11.             <button type="submit">Pesquisar</button>
  12.         </form>
  13.  
  14.         <h2>Listagem de Contatos</h2>
  15.         <?php
  16.             $nome = '';
  17.             if (isset($_POST['nome'])){
  18.                 $nome = $_POST['nome'];
  19.             }
  20.        
  21.             /* Conectando com o banco de dados para listar registros */
  22.             $datasource = 'mysql:host=localhost;dbname=agenda';
  23.             $user = 'root';
  24.             $pass = 'vertrigo';
  25.             $db = new PDO($datasource, $user, $pass);
  26.    
  27.             $query = "SELECT * FROM contato WHERE nome LIKE '%$nome%'";
  28.             $stm = $db -> prepare($query);
  29.            
  30.             if ($stm -> execute()) {
  31.                 print "<table border>
  32.                             <tr>
  33.                                 <th>Nome</th>
  34.                                 <th>Email</th>
  35.                                 <th>Telefone</th>
  36.                                 <th>Ações</th>
  37.                             </tr>";
  38.                 while ($row = $stm -> fetch()) {
  39.                     $id = $row['contatoid'];
  40.                     $nome = $row['nome'];
  41.                     $email = $row['email'];
  42.                     $telefone = $row['telefone'];
  43.    
  44.                     print "<tr>
  45.                                 <td>$nome</td>
  46.                                 <td>$email</td>
  47.                                 <td>$telefone</td>
  48.                                 <td>
  49.                                     <a href='delete.php?id=$id'>Delete</a> |
  50.                                     <a href='edita.php?id=$id'>Edita</a>
  51.                                 </td>
  52.                             </tr>";            
  53.                 }
  54.                 print "</table>";
  55.             } else {
  56.                 print '<p>Erro ao listar!</p>';
  57.             }
  58.         ?>
  59.         <a href='index.php'>Voltar</a>
  60.     </body>
  61. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement