2015-12-01 77 views
1

我从脚本收到以下错误。PHP错误未定义的索引,搜索脚本

[Tue Dec 01 09:17:10 2015] [error] [client xxxx] PHP Notice: Undefined index: search in xxx/search.php on line 3, referer: http://xx/ 

此外,我碰到下面的错误,有时还有

PHP Notice: Undefined offset: 4 in xxx/search.php on line 21, referer: http://xxx/search.php?search=C8053A-B&submit=Search 

为search.php中的代码是

<?php 
// Words 
$words = trim($_GET["search"], ' '); 
echo '<br>'; 
echo '<div align="center">'; 
echo '<form method="get" action="search.php?" id="searchform">'; 
echo '<input type="text" name="search">'; 
echo '<input type="submit" name="submit" value="Search">'; 
echo '</form>'; 
echo '</div>'; 
if ($words != '') 
{ 
echo 'Search Results for <b>'.$words.'</b>:'; 
$file = fopen('inv.csv', 'r'); 
$crossw = $words; 
$words = array($words); 
$words = array_map('preg_quote', $words); 
$regex = '/'.implode('|', $words).'/i'; 
print('<table border="1"><tr><td width="150">Primary Part #</td><td width="75">Price</td><td width="75">Qty Avail</td><td width="105">Searched #</td><td width="375">Description</td></tr></table>'); 
while (($line = fgetcsv($file)) !== FALSE) { 
list($part, $price, $qty, $cross, $desc) = $line; 
if(preg_match($regex, $cross)) { 
    print('<table border="1"><tr><td width="150">'.$part.'</td><td width="75">'.$price.'</td><td width="75">'.$qty.'</td><td width="105">'.$crossw.'</td><td width="375">'.$desc.'</td></tr></table>'); 
} 
} 
if ($crossw != '') 
{ 
echo 'End of results.'; 
}} 
?> 

我想摆脱错误的没有关闭记录我的php.ini。

错误的来源/原因是什么?

+0

[PHP的可能重复:“请注意:未定义的变量”和“注意:未定义索引”](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Sean

+1

'if(isset($ _ GET [“search”]) )'是你的朋友 – Sean

+0

它可能是你没有访问页面的查询字符串搜索例如:'http://yourpage.com/?search = blabla'因为肖恩提及'isset'是要走的路:) –

回答

1

本通知邀请您考虑可能不会始终设置search url参数(也许当您第一次浏览该搜索页时?)。

$words = trim($_GET["search"], ' '); 

你在这里假设̀$_GET["search"]变量始终是供您使用,这是情况并非如此。

这种情况下,应适当在PHP与isset()处理与三元运营商构建(简写为if/else语句),像这样:

$words = isset($_GET["search"])?trim($_GET["search"], ' '):''; // $words will be set to an empty string in case the search param is not set. 
+0

谢谢你解决这个问题。正如我所说我是一个完全新手,但试图学习! – Jesse

+0

不用客气,请考虑接受答案。 – Calimero

+0

只要我找到了,我会尽快做!对未定义的偏移错误有任何想法? – Jesse