返回查询结果的函数

时间:2016-12-11 10:36:18

标签: php mysql

假设我有一个名为 mytable 的表,其中包含列:

------------------------
| id | field1 | field2 |
------------------------

并假设我有一个html文件:

<body>
<?php 
    include ('connect-db.php');
    include ('function.php');
?>

<ul>
    <?php 
        myfunction();

        while($row  = $result->fetch_assoc()){
            echo "<li>".$row['field1']." and ". $row[field2]."</li>";
        }
    ?>
</ul>
</body>

这是我的connect-db.php文件:

<?php
$servername = "localhost";
$username   = "root";
$password   = "root";
$dbname     = "dbname";

$conn=new mysqli($servername, $username, $password, $dbname);
?>

这是我的function.php文件:

<?php
    function myfunction(){
        $sql    = "SELECT * FROM mytable";
        $result = $conn->query($sql);
    }
?>

如何回显field1和field 2?因为我有错误

2 个答案:

答案 0 :(得分:0)

  

函数内使用的任何变量默认限制为本地   功能范围。

您可以在此处详细了解:Variable scope。怎么解决?将$conn作为myfunction的参数传递,并返回$result

function myfunction(mysqli $conn) {
    $sql    = "SELECT * FROM mytable";
    return $conn->query($sql);
}

然后你可以用

来调用它
$result = myfunction($conn);

答案 1 :(得分:0)

确保以下更改.....

在主页

  <body>
  <?php 
      include ('connect-db.php');
      include ('function.php');
  ?>

  <ul>
      <?php 
         $result= myfunction();

          while($row  = $result->fetch_assoc()){
              echo "<li>".$row['field1']." and ". $row[field2]."</li>";
          }
      ?>
  </ul>
  </body>

在您的函数文件中..

      <?php
      include ('connect-db.php');
      function myfunction(){
          $sql    = "SELECT * FROM mytable";
          $result = $conn->query($sql);
          return $result;
      }
  ?>