如何在不同的页面中调用fetch查询函数(PHP)

时间:2018-06-03 18:00:58

标签: php function oop mysqli

我写了下面的代码,数据没有提取。可以有人请帮助我。我主要做程序编程,所以我对oops没有那么多的知识。

1.xyzconfig.php

define("HOST", "localhost");            
define("USER", "root");             
define("PASSWORD", "");     
define("DATABASE", "end");           

2.dbconnect.php

include_once 'xyzconfig.php';   

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

if($mysqli->connect_error) 

{

header("Location: ../error.php?err=Unable to connect to MySQL");

exit();

}

3.function.php

include_once 'xyzconfig.php';   

 function user_fetch($mysqli)

{

    if($stmt=$mysqli->prepare("SELECT id, username,email,role FROM members"))
    {
        $stmt->execute();   

        $stmt->store_result();

         if($stmt->num_rows == 1)

         {

          while($row=$stmt->fetch_assoc() )
          {

            echo "<tr><td>".$row["id"]."</td><td>".$row["username"]." ".$row["email"]." ".$row['role']."</td></tr>";

          }

        }    
    }}

4.test.php

include_once 'includes/db_connect.php';

include_once 'includes/functions.php';

echo user_fetch($mysqli);

1 个答案:

答案 0 :(得分:0)

functions.php需要包含dbconnect.php而不是xyzconfig.php

include_once 'dbconnect.php';   

 function user_fetch($mysqli)

{

    if($stmt=$mysqli->prepare("SELECT id, username,email,role FROM members"))
    {
        $stmt->execute();   

        $stmt->store_result();

         if($stmt->num_rows >= 1)

         {

          while($row=$stmt->fetch_assoc() )
          {

            echo "<tr><td>".$row["id"]."</td><td>".$row["username"]." ".$row["email"]." ".$row['role']."</td></tr>";

          }

        }    
    }}

test.php需要:

include_once 'includes/dbconnect.php';

include_once 'includes/functions.php';

echo user_fetch($mysqli);

使用store_result()

绝对没有意义