从数据库获取值并从另一个文件回显

时间:2019-04-18 04:04:23

标签: php

我正在尝试从数据库表中选择一行,并在另一个PHP文件中显示变量。现在,我只需要尝试一个变量,但是稍后将更改为输出表。错误是未定义的变量:输出。

我尝试使用会话,但是它会打印出数组,并且不会一直进行下去。我真的只是想要该变量,以便可以将它们轻松放入表中。

我的商店文件,该文件在搜索栏下显示一个搜索栏,并在其中显示结果。

<?php
  require "header.php";
?>

<main>

<form action="includes/itemsearch.php" method="get">
  Please enter the Item you are looking for:<br>
  <input type="text" name="item" placeholder="Search for an item...">
  <br><br>
  <button type="submit" name="search-submit">Search</button>
</form>
<?php echo $output ?>
</main>



<?php
  require "footer.php";
?>

我的物品搜索文件:

<?php
if (isset($_GET['search-submit'])) {
  require 'connect.php';


  $item = $_GET['item'];
  $output = "";

  $sql = "SELECT * FROM Product";

  $result=mysqli_query($conn,$sql);
  while($row=mysqli_fetch_array($result)){
    $pName =$row['Product_Name'];
    $manufacture=$row['Manufacture'];
    $quantity=$row['Quantity'];
    $price=$row['Price'];
    $description=$row['Description'];
    echo"<p>$pName</p><br />";
  }
  header("Location: ../store.php?");

}

我目前收到未定义的变量错误。

2 个答案:

答案 0 :(得分:0)

$ output是未定义的,因为您在单击提交按钮时对其进行了初始化,因此<?php echo $output ?>首先执行,然后对其进行初始化。

尝试

<?php 
     if (isset($_GET['search-submit'])){
          echo $output;
     }
?>

要获取输出,只需在store.php中搜索文件

// store.php

<?php
  require "header.php";
  require "search.php";
?>

<main>

<form action="" method="get">
  Please enter the Item you are looking for:<br>
  <input type="text" name="item" placeholder="Search for an item...">
  <br><br>
  <button type="submit" name="search-submit">Search</button>
</form>
<?php echo $output ?>
</main>



<?php
  require "footer.php";
?>

这是最终代码

// search.php
<?php
    if (isset($_GET['search-submit'])) {
      require 'connect.php';


      $item = $_GET['item'];
      $output = "";

      $sql = "SELECT * FROM Product";

      $result=mysqli_query($conn,$sql);
      while($row=mysqli_fetch_array($result)){
        $pName =$row['Product_Name'];
        $manufacture=$row['Manufacture'];
        $quantity=$row['Quantity'];
        $price=$row['Price'];
        $description=$row['Description'];
        $output .= "<p>$pName</p><br />";
      }

    }

?>

// store.php
<?php
  require "header.php";
  require "search.php";
?>

<main>

<form action="" method="get">
  Please enter the Item you are looking for:<br>
  <input type="text" name="item" placeholder="Search for an item...">
  <br><br>
  <button type="submit" name="search-submit">Search</button>
</form>
<?php echo isset($_GET['search-submit']) ? $output : '' ?>
</main>



<?php
  require "footer.php";
?>

答案 1 :(得分:0)

使用post方法而不是

<?php
if (isset($_POST['search-submit'])) {

}
?>