Untitled

 avatar
unknown
php
9 months ago
2.1 kB
4
Indexable
<form method="GET" action="">
  <input type="text" name="query" placeholder="Pesquisa...">
  <label>
    <input type="checkbox" name="type[]" value="posts"> Posts
  </label>
  <label>
    <input type="checkbox" name="type[]" value="comments"> Comentários
  </label>
  <label>
    <input type="checkbox" name="type[]" value="users"> Usuários
  </label>
  <button type="submit">Pesquisar</button>
</form>

<?php
if (isset($_GET['query']) && isset($_GET['type'])) {
    $query = $_GET['query'];
    $types = $_GET['type'];

    // conexão com o banco de dados
    $conn = new mysqli("localhost", "userdb", "userpass", "wordpress");

    if ($conn->connect_error) {
        die("Conexão falhou: " . $conn->connect_error);
    }

    $results = [];

    // pesquisa nos tipos selecionados
    foreach ($types as $type) {
        switch ($type) {
            case 'posts':
                $sql = "SELECT * FROM posts WHERE title LIKE ? OR content LIKE ?";
                break;
            case 'comments':
                $sql = "SELECT * FROM comments WHERE content LIKE ?";
                break;
            case 'users':
                $sql = "SELECT * FROM users WHERE username LIKE ? OR email LIKE ?";
                break;
            default:
                continue 2;
        }

        $stmt = $conn->prepare($sql);
        $likeQuery = "%" . $query . "%";
        if ($type == 'posts' || $type == 'users') {
            $stmt->bind_param("ss", $likeQuery, $likeQuery);
        } else {
            $stmt->bind_param("s", $likeQuery);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $results[$type][] = $row;
        }
        $stmt->close();
    }

    $conn->close();

    // exibi resultados
    foreach ($results as $type => $items) {
        echo "<h2>Resultados para " . ucfirst($type) . ":</h2>";
        foreach ($items as $item) {
            echo "<pre>";
            print_r($item);
            echo "</pre>";
        }
    }
}
?>
Editor is loading...
Leave a Comment