简体   繁体   English

返回查询结果的函数

[英]function that return query result

assume that i have a table named mytable with columns: 假设我有一个名为mytable的表,其中包含列:

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

and assume i have a html files: 并假设我有一个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>

this is my connect-db.php file: 这是我的connect-db.php文件:

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

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

and this is my function.php file: 这是我的function.php文件:

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

How to echo the field1 and field 2? 如何回显field1和field 2? because i have and error 因为我有错误

Any variable used inside a function is by default limited to the local function scope. 函数内使用的任何变量默认限制为本地函数范围。

You can read more about it here: Variable scope . 您可以在此处阅读更多相关信息: 可变范围 How to fix it? 怎么解决? Pass the $conn as an argument of myfunction , and return the $result . 传递$conn作为myfunction的参数,并返回$result

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

then you can call it with 然后你可以用它来调用它

$result = myfunction($conn);

Make sure the following changes..... 确保以下更改.....

at main page 在主页面

  <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>

At your function file.. 在你的功能文件..

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM