Jump to content

php mysql search function problem


lukelee

Recommended Posts

hi, guys, here is my search code, there are 3search options to choose: author name, book title, keywords. my problem is whatever which option people choose, it search from all 3 options, for example: if i select author name, and type 'luke', the system searchs luke not only from author name, also from book title, and keywords. can anyone take a look at my codes, and tell me whats wrong.

 

<?php

$search = $_POST['find'];

if ($searching =="yes")
{
echo "<h2>Results</h2><p>";

if ($search == "")
{
echo "<p>You forgot to enter a search term</p>";
exit;
}

require_once('db.php');


$query = "SELECT book_id, book_title,author,keyword FROM book WHERE book_title LIKE '%$search%' OR author LIKE '%$search%' OR keyword LIKE '%$search%'";
$numresults=mysql_query($query);

}
?>
<table border='1'width='500'>
	<tr>
            <td>Book Id</td>
		<td>Book Title</td>
		<td>Author</td>
				</tr>
                    <?php
while($result = mysql_fetch_array( $numresults))
{
echo("<tr>");
echo("<td>$result[book_id]</td>");
echo("<td>$result[book_title]</td>");
echo("<td>$result[author]</td>");
echo("</tr>");

}
?>
</table>
<?php
$numrows=mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}

echo "<b>Searched For:</b> " .$find;
?>

<form name="search" method="post" action="<?php echo $PHP_SELF ?>">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="aname">Author Name</option>
<Option VALUE="title">Book Title</option>
<Option VALUE="keyword">Keyword</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>

Link to comment
https://forums.phpfreaks.com/topic/125262-php-mysql-search-function-problem/
Share on other sites

Hi,

 

Need to add script to check user selections and the query has to be formed as,

 

<?php
$query = "SELECT book_id, book_title,author,keyword FROM book";

if($_POST['field']=='aname')
$query .= " WHERE author LIKE '%$search%'";
elseif($_POST['field']=='title')
$query .= " WHERE book_title LIKE '%$search%'"
elseif($_POST['field']=='keyword')
$query .= " WHERE keyword LIKE '%$search%'"
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.