PHP Search with OOP PDO



Here is an example of how you might implement a page search feature using PHP, PDO, and OOP:

class Search {

    private $pdo;


    public function __construct($pdo) {

        $this->pdo = $pdo;

    }


    public function search($searchTerm) {

        $searchTerm = "%$searchTerm%";

        $query = "SELECT * FROM pages WHERE content LIKE :searchTerm";

        $stmt = $this->pdo->prepare($query);

        $stmt->execute(['searchTerm' => $searchTerm]);

        return $stmt->fetchAll();

    }

}

In this example, the search() function performs a search on a table called "pages" for a column called "content" where the value of "content" is like the search term. The search term is passed in as a parameter to the function, and it is used in a prepared statement to search the table. The function returns an array of rows that match the search term.

<?php

require_once 'Search.php';


try {

    $pdo = new PDO("mysql:host=localhost;dbname=yourdbname", "username", "password");

    $search = new Search($pdo);

    $searchTerm = $_GET['searchTerm'];

    $results = $search->search($searchTerm);

} catch (PDOException $e) {

    echo "Error: " . $e->getMessage();

}

?>

You can then display the results on the page using a loop:

<form action="search.php" method="GET">

  <input type="text" name="searchTerm" placeholder="Search...">

  <button type="submit">Search</button>

</form>


<?php if (count($results) > 0) { ?>

    <h2>Search Results</h2>

    <?php foreach ($results as $row) { ?>

        <div class="result">

            <h3><?php echo $row['title']; ?></h3>

            <p><?php echo $row['content']; ?></p>

        </div>

    <?php } ?>

<?php } else { ?>

    <p>No results found.</p>

<?php } ?>

In this example, we first check if there are any results found, if so we display the title and the content of each page that matches the search term. If not we display a message "No results found."