I got this codes for search and I'm having a problem. It functions well but after I clicked the search tab, it displays errors. But if I tried entering queries for search, it works fine.
These are the errors:
Notice: Undefined index: searching in F:\Programs\wamp\www\a\search.php on line 45
Notice: Undefined index: find in F:\Programs\wamp\www\a\search.php on line 46
Notice: Undefined index: field in F:\Programs\wamp\www\a\search.php on line 47
Here is the codes:
<h2>Search</h2>
<form name="search" method="post" action="search.php">
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="firstname">First Name</option>
<Option VALUE="lastname">Last Name</option>
<Option VALUE="location">Location</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
<?php
$searching = $_POST['searching'];
$find = $_POST['find'];
$field = $_POST['field'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("chess") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM members WHERE upper($field) LIKE'%$find%'");
echo "<table border=1>";
echo "<tr><td>Codename</td><td>Location</td><td>Rating</td></tr>";
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['firstname'];
echo " ";
echo $result['lastname'];
echo "<br>";
echo $result['location'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
You need to check if your $_POST
variables are set by using isset()
because they are not set when you haven't posted anything. That is what is causing the notice to appear.
So you need to do something like:
$searching = isset($_POST['searching']) ? $_POST['searching'] : '';
$find = isset($_POST['find']) ? $_POST['find'] : '';
$field = isset($_POST['field']) ? $_POST['field'] :