The complete search engine

The search engine now successfully allows the user to search for a specific word or quote, it will then redirect the user to the post page with the list of posts which have what they have searched for. This is a good method to have on our website as it means if our target audience of students want to quickly find a post they liked then instead of scrolling through loads of recent posts they can easily navigate to a smaller selection with the words they chose to search. Like in the example below we can search for “hello” and filter to just one post with this included. The code I used to complete this process is shown below.

In the index.php


<?php
if(isset($_POST["sort"])) {
$sort = $_POST["sort-by"];

if(strcmp($sort, "new") == 0) {
$query = "SELECT * FROM posts ORDER BY id DESC";
} else {
$query = "SELECT * FROM posts ORDER BY id ASC";
}
} else {
if(isset($_POST["search"])) {
$searchTerm = $_POST["search"];
$query = "SELECT * FROM posts WHERE post LIKE '%{$searchTerm}%' ORDER BY id DESC";
} else {
$query = "SELECT * FROM posts ORDER BY id DESC";
}
}

$result = mysqli_query($connect, $query);
if(!$result) {
die("Query Error");
}
?>

search_page.php


<div class="box_hello"><a>Hello, <?php echo ucfirst($_SESSION["user"]); ?>! </a></div>
</div>



<form class= "search" action="index.php" method="post">
<p>Search</p><input type="text" name="search" placeholder="Search by words..." pattern="[^'\x22]+" title="Invalid input">
<input type="submit" value="Go!" />
</form>
<?php } ?>

searchy

Above:The search page

searchy2

Above: Inputting the search criteria “hello”

searchy3

Above: Returning the search results on the posting page.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s