2014-01-09 81 views
-1

我得到了这个代码的搜索,我有一个问题。它运行良好,但是当我点击搜索标签后,它显示错误。但是,如果我尝试输入查询搜索,它工作正常。未定义的索引[php]

这些都是错误的:

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 

这里是代码:

<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; 
} 



?> 

回答

1

你需要检查,如果你的$_POST变量通过使用isset()设置,因为它们没有设置,当你的天堂” t发布任何东西。这是导致通知出现的原因。

所以,你需要做的是这样的:

$searching = isset($_POST['searching']) ? $_POST['searching'] : ''; 
$find = isset($_POST['find']) ? $_POST['find'] : ''; 
$field = isset($_POST['field']) ? $_POST['field'] : 
+1

它的工作原理。谢谢:)在10分钟内不能接受答案。我稍后会接受它。 – pingboo23

+0

欢迎您:) – putvande

1

您可以使用isset()但在这里,你正在使用POST方法用于搜索结果,您应该使用GET所以使用GET方法而不是POST和仍然请确保您使用isset()作为$_GET以及

if(isset($_GET['searching'])) { 
    //Some code 
} 
+1

'$ _GET'?该表单具有'method =“post”'。 – putvande

+0

@putvande阅读答案,不只是代码 –

+1

好的。我想我很早就发表评论。 – putvande