0
Search
im planning on creating/placing a search bar for my website. but i really dont know how to use mysql and php for that specific action(not that good at php and data manipulation) can you please provide a simple example of search. thank you so much.
2 odpowiedzi
+ 1
You need to decide on how you want to handle the search. For example,
- when the user enters the search term into the input, should it take them to a new page to show results.
- when the user enters the search term into the input, should it auto populate with results based on the current characters?
- when the user enters the search term into the input, should it run the search query and return data back to the current page.
All of these things are important because if its the first option, then a simple form action to the php file will be sufficient, and then either show the results on the same query page, or header refresh them to a new results page.
But if its any of the other two options, then you would want to use AJAX to post and handle the request. This way, the user never actually leaves the page or see's anything being processed. It will simply return the results from the query back via Ajax and you can then map that to a innerHTML of a div tag or something. Same thing for the auto populate, post via Ajax on a keyChange of the input to query where something is LIKE.
Which brings me onto the PHP query. To search something simply use LIKE, so you will get the $searchterm =$_POST['my-search-input-id']; and then within the query use, FROM table WHERE column1 LIKE :searchterm OR column2 LIKE searchterm etc etc.
I hope this helps you out.
0
First you need to create a table that contains both the link and the title of the pages you want to search:
In phpMyAdmin, create the table:
CREATE TABLE articles (
Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Link VARCHAR(255),
Title VARCHAR(255)
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB
In this example, I used utf8 and the innoDB engine, but you can change them to whatever you like.
Now, if you use a controller for your pages, do it this way.
In your html file (e.g. search.html), create the search form:
<form method=”GET” action=””>
<input type=”search” name=”searchform”>
<input type=”submit” value=”search”>
</form>
make sure that get is set
if(isset($_GET[‘title’]) AND $_GET[‘title’] != ‘’){
//sql statement
}
In your php controller (index.php), type:
I assume that you are already able to connect with the database, so I pass directly to the query
$sql = ‘SELECT link, title FROM articles WHERE title LIKE %’ . $_GET[‘title’] . ‘%’;
so, when you type a few words in the search box, it will only return the results containing the word entered.