Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  20] [ 5]  / answers: 1 / hits: 34943  / 12 Years ago, tue, march 27, 2012, 12:00:00

Not sure if this is against stackoverflow rules as it's not a specific code question but I really need a little help.



I want to know if it is possible to create a search feature (search box) on an HTML webpage that will query a database and return the results?



Basically I have a database of products and their related categories. A user would come to the website, enter the category in the search field...somehow query the database and return the results on a new page.



Note: the results page doesn't have to be HTML (could be PHP etc).



If you could also include a little guidance on how (please nothing detailed, just need a direction).
Thank you!


More From » html

 Answers
14

Yeah, sure, that's pretty easy.



Here's what I would do:



On your first page:



<form action=mypage.php?searching=true method=POST>
<input type=text name=searchcategory value=/>
<input type=submit value=Search/>
</form>


On mypage.php:



<table>
<?php
$sql=$db->prepare('SELECT * FROM mytable WHERE category=:category');
$sql->execute(array(':category'=>$_REQUEST[searchcategory]));

while ($row=$sql->fetch())
{
//Here is where you will loop through all the results for your search. If
//you had for example for each product name, price, and category,
//you might do the following
echo <tr><td>$row[name]</td><td>$row[price]</td><td>$row[category]</td></tr>;
}
?>
</table>


NOTES:




  • I use mySQL...I'm not sure how you would do it with something else, but I would guess you could adapt the code for another sort of database.


  • I generally use the PDO (accessing through prepare and execute)...my teacher said it was more secure. You can change that part of the code to however you connect to your DB. The code I use to connect looks something like (goes before the code above on mypage.php):



    try {
    $db = new PDO(mysql:host=localhost;dbname=mydatabasename,username,password);
    } catch (Exception $e) {
    echo PDO connection error: . $e->getMessage();
    exit(1);
    }

  • They don't actually have to be separate pages. If you had both pages php (the first one not straight HTML), you could just change the content based on whether a variable (maybe called searching) was set to true or false.




Let me know if any of that is unclear, and I'd be happy to help you out. Good luck! :)


[#86594] Saturday, March 24, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
dequant questions
;