PHP $_POST 数组中的未定义索引

3
我是一名有用的助手,可以为您翻译文本。
我有一个名为index.php的页面,其中添加了一个与数据库连接的搜索表单。因此,当用户搜索任何单词时,结果将从数据库中显示出来。一旦在页面上生成结果,我希望用户将结果导出到.doc文件中。
我只想将查询结果放入.doc文件中,但由于某些原因,我得到了一个空白的.doc文件。
以下是我的代码:
搜索表单:
<form id="searchform" method="post">
    <input type="text" name="searchit" id="searchit" class="txt"  />
    <input type="submit" value="Search" id="button" class="button" />
</form>

查询:

<?php
include("database.php");
   $term = strip_tags(substr($_POST['searchit'],0, 100));
   $term = $mysqli->real_escape_string($term); 

   if($term=="") {
     echo "<div class='error'>Enter Something to search</div>";
     exit();
   }

   termcheck($term, $mysqli);             
   function termcheck($term, $mysqli){
     $qry="Select * from pogel where title = '$term'";
     if($result = $mysqli->query($qry)){

       $num_rows = $result->num_rows;
         if($num_rows > 0) {

           while($row = $result->fetch_assoc())
             {
               echo "Stem : ".$row['title']."<br>";
             }

         }
}
}
?>

1
你的HTML页面上是否有一个名为'searchit'的元素,它会发送POST数据? - Phiter
是的,“searchhit”已经在我的搜索页面上了,但仍然出现以上错误。 - Mehreen
1个回答

1
似乎您在POST中没有这个键。如果脚本中没有这样的元素,您可以尝试这个。
$searchit = filter_input(INPUT_POST, 'searchit');

if(!$searchit) {
  echo "<div class='error'>Enter Something to search</div>";
  exit();
}

$term = strip_tags(substr($searchit,0, 100));
$term = $mysqli->real_escape_string($term); 

尝试使用以下方法生成文档文件:

<?php
include("database.php");
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = $mysqli->real_escape_string($term); 

if($term=="") {
    echo "<div class='error'>Enter Something to search</div>";
    exit();
}

$output = termcheck($term, $mysqli);

function termcheck($term, $mysqli){
    $qry = "Select * from pogel where title = '$term'";
    $result = '';

    if($result = $mysqli->query($qry)){
        $num_rows = $result->num_rows;
        if($num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $result .= "Stem : ".$row['title']."<br>";
            }
        }
    }

    return $result;
}

ob_flush();

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

echo $output;

//ob_flush_clean() might be useful here, but not sure
?>

你的代码修复了那个错误,但不幸的是,我得到了一个空白页面,并且查询没有返回任何结果。 - Mehreen
刚刚更新了我的问题和代码,请再次检查! - Mehreen
谢谢。这是同一个文件,包含HTML和PHP吗? - Denis Alexandrov
是的,同一个文件,我的结果显示在网页上,但当我点击“导出为MS Word”按钮时,我能够生成一个空白的.doc文件。 - Mehreen
我已经分享了我的表格和查询。运行.doc文件的查询是否还需要其他操作?我的查询在网页上可以工作,但在.doc文件上无法工作。也许有什么好的教程可以供我参考或其他帮助吗? - Mehreen
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接