输入名称以两种不同的形式更改,导致名称取消错误

时间:2017-03-26 19:58:42

标签: php html forms

我有错误,我无法解决。我有两个提交按钮的表单:

<form name="form_1"  action=<?php echo $_SERVER['PHP_SELF'] ;?>>
    <input type="text" name="search_1" value="<?php echo $_GET['search'] ; ?>">
    <input type="submit" value="Search by Name">
    </form>

<form name="form_2"  action=<?php echo $_SERVER['PHP_SELF'] ;?>>
    <input type="text" name="search_2" value="<?php echo $_GET['search'] ; ?>">
    <input type="submit" value="Search by Message">
    </form>

错误说明:search_1未定义。怎么可能未定义? 顺便说一句,如果我将两个表单输入名称相同:search一切正常,但正常情况下,如果我将值放在一个表单中,请以其他形式获取相同的输入。 我做错了什么?

form_1的php代码:

    <?php


    // Check if the form has been sent or if the page was accessed using the GET method.
  if( filter_input( INPUT_SERVER, "REQUEST_METHOD" ) !== "GET" ) {
    die();
  }

  $search = filter_input( INPUT_GET, "search" );

  //  Check if the searh input has been correctly fill
  if( !isset( $search ) ) {
    die();
  }
  // Let's return here to prevent open an empty file
  if( filesize( $file ) <= 0 ) {
    return;
  }

  $openedFile = fopen( $file, "r" );

  // I was using the here document option, echo <<<END END; but it didn't work due to my text editor...
  echo "
  <table width=50% border=1>
    <thead>
      <tr>
        <th>Name</th>
        <th>Nick</th>
        <th>Message</th>
      </tr>
    </thead>
    <tbody>
  ";

  // Let's save in buffer the current line and then navigate through all of them

  while( ( $buffer = fgets( $openedFile, 4096 ) ) !== false ) {


  $part = explode( "|", $buffer );
    // Here we check if the line has the searched word
    if( strpos( $part[0], $search ) !== false && $search != '') {

      echo "
          <tr>
            <td>" . $part[0] . "</td>
            <td>" . $part[1] . "</td>
            <td>" . $part[2] . "</td>
          </tr>
      ";

    }//.if
  }//.while

  echo "
    </tbody>
  </table>
  ";
?>

1 个答案:

答案 0 :(得分:0)

您正在打印$_GET数组中的值而不进行检查,是否在URL中传递了该值。

看,当您提交包含名称search_1的第一个表单时,此时search_2不能在$_GET数组中设置,但是您在输入中打印它而不检查。因此,当您提交一个表单时,它会以另一种形式提供错误。

试试这个 -

<form name="form_1"  action=<?php echo $_SERVER['PHP_SELF'] ;?>>
    <input type="text" name="search_1" value="<?php echo isset($_GET['search_1'])?$_GET['search_1']:"" ; ?>">
    <input type="submit" value="Search by Name">
</form>

<form name="form_2"  action=<?php echo $_SERVER['PHP_SELF'] ;?>>
    <input type="text" name="search_2" value="<?php echo isset($_GET['search_2'])?$_GET['search_2']:"" ; ?>">
    <input type="submit" value="Search by Message">
</form>