I have a database table named with books. it consists of something like below
ex database given below,
user is trying to search the value by author or title and based on category
ex: if user search for adapt by selecting fiction need display both adapt and adaxx
below is the code for search and
using mysql database

<form action="search.php" method="post">
<?php
$select_query=          "Select distinct category from books";
$select_query_run =     mysql_query($select_query);
$select_query_array=   mysql_fetch_array($select_query_run) ;
 $cat = $select_query_array['category'];
echo "<select name='name'>";
while ($select_query_array=   mysql_fetch_array($select_query_run) )
{// dynamic drop list

  echo "<option value='".htmlspecialchars($select_query_array["category"])."' >".htmlspecialchars($select_query_array["category"])."</option>";
}

echo "</select>";
?>
   <input type="text" name="searchvalue" size="5"  id="searchfield" title="searchfield" onFocus="clearText(this)"/>
     <input type="submit" name="submit" value="" alt="Search" id="searchbutton" title="Search" />
</form>
<?php
$button = $_POST['submit'];
$search = $_POST['searchvalue']; 
if(strlen($search)<=1)
{
$name = $_POST['name'];
//echo $a;
echo "Search term too short";
}
else{
echo "You searched for $search <hr size='1'></br>";
$search_exploded = explode (" ", $search);
$x = "";
$construct = "";  
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";

}
$construct ="SELECT * FROM books WHERE $construct and category = '$name'";// I tried this but not working

$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for $search.</br></br>1.";
else
{
echo "$foundnum results found !<p>";
}
?>

If I understand what you're asking, you need to break this up into two steps. First, have the user select the category and submit the form. Then, using $_POST['category'], present the user with options based on SELECT author, title FROM books WHERE category=" . $category . '"'.

To make it better, you can use javascript to auto-submit the form and AJAX to populate the selects without submitting the whole page.

Also, you should be using mysqli or pdo instead of mysql, and you should secure any user inputs that go to the database, ex: $category=mysqli_real_escape_string($_POST['category']);

thank you very much your replay, I didn't check your query
SELECT author, title FROM books WHERE category=" . $category . '"'.
Istead I used This
$construct = "SELECT * FROM books WHERE category = '$name' AND (title LIKE '%$search%' or author LIKE '%$search%')";
Now its working....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.