I am quite new to PHP and have been following tutorials and notes so far and have run into a problem.The goal is to create an e-commerce website. One function must be to search the database and display products which I can do. These results must then be able to be sorted (by price/name etc.) I can sort the products however I cannot sort the results f the search as I lose the searched term when reloading. Any help on fixing this or improving the work would be fantastic. Here is what I have so far..
<div id = "form">
<form action="search3.php" method="get" enctype="multipart/form-data">
Search: <input type="text" name="term" /><br />
<input type="submit" name = "search" value="Submit" />
</form>
</div>
The form above stores "term" the searched term.
<?php
$term = pg_escape_string($_REQUEST['term']);?>
<p>You Searched for:</p><?php Print $term; ?>
<br><br>
Sort by
<form method=get style="display: inline;" name='orderby_form'>
<input type=hidden name='param1' value="<?php print $param1; ?>">
<input type=hidden name='param2' value="<?php print $param2; ?>">
<select name=orderby onChange="orderby_form.submit();">
<option value='none'>v-v-v</option>
<option value='title'>Title</option>
<option value='price_asc'>Price (Low - High)</option>
<option value='price_desc'>Price (High - Low)</option>
</select>
</form>
This gives options on how the user wants to sort the data
<?php
$selected = array();
$orderby = $_GET['orderby'];
if(!$orderby)
{ $orderby = ''; }
if($orderby == 'price_asc')
{
$orderby_query = "order by price asc";
}
else if($orderby == 'price_desc')
{
$orderby_query = "order by price desc";
}
else if($orderby == 'title')
{
$orderby_query = "order by title";
}
else { unset($orderby); }
// If $orderby was valid set the selected sort option for the form.
if($orderby)
{
$selected[$orderby] = 'selected';
}
// Now run your SQL query with the $orderby_query variable. Ex:
$query = "SELECT * FROM products WHERE (title LIKE '%$term%' OR description LIKE '%$term%') $orderby_query";
// SQL code goes here..
$result = pg_query($query);
if(pg_num_rows($result) == 0) {
echo "No records found";
}
else{
while ($row = pg_fetch_assoc($result)) {
?>
After the final bit here I just print the results into tables
These two pictures show the search results. The first prints all products with "bass" in the title/description and is unsorted. http://oi61.tinypic.com/28clzqs.jpg
The second is when I sort the data.The search 'term' is lost and ALL products become sorted. http://oi59.tinypic.com/34g39tu.jpg
Simple enough work around. Thanks to Sean for showing me. "add your $term to the 2nd form"
Which is
<input type=hidden name='param2' value="<?php print $param2; ?>">
//Added -VV-
<input type=hidden name='term' value="<?php print $term; ?>">
Works perfectly well now.