无法正确返回并存储我的mysqli结果

时间:2015-09-03 12:17:50

标签: php

我正在尝试返回我的mysqli结果并将其存储在静态变量中,以便我可以将其传递给另一个函数。如下所示,第二个函数需要能够从第一个函数中读取结果。范围问题应该已经修复,返回并存储它然后将我的函数存储在第二个函数内的变量中:

我做错了什么?为什么这不起作用?它适用于我的数据库连接。

    function profile_info() {
            $connection = database();
            static $result;

            $query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
                      FROM users";
            $result = mysqli_query($connection, $query);
            return $result;
    }

然后我将返回的结果存储在我的函数中`$ result = profile_info():

function users_overview () {
    $connection = database();

    $result = profile_info();

    echo "<div id='users_overview'>";
    while($row = mysqli_fetch_array($result)) {

        if (!empty($row['status']) && $row['status'] == 'Online') {
            $status = "<div class='online'></div>"; 
        }
        else {
            $status = "<div class='offline'></div>";
        }

    include 'php/core/age_converter.php';

    include 'php/includes/profile_information.php';

    }
    echo "</div>";
}
users_overview();

2 个答案:

答案 0 :(得分:1)

当您从$connection = database();

包含对profile_info();的来电时,似乎有两次users_overview ()被调用

现在检查它是否有效,

function profile_info() {
                $connection = database();
                static $result;

                $query = "SELECT id, name, first_name, last_name, birthdate, occupation, status
                          FROM users";
                $result = mysqli_query($connection, $query);
                return $result;
        }



    function users_overview () {

        $result = profile_info();

        echo "<div id='users_overview'>";
        while($row = mysqli_fetch_array($result)) {

            if (!empty($row['status']) && $row['status'] == 'Online') {
                $status = "<div class='online'></div>"; 
            }
            else {
                $status = "<div class='offline'></div>";
            }

        include 'php/core/age_converter.php';

        include 'php/includes/profile_information.php';

        }
        echo "</div>";
    }
    users_overview();

答案 1 :(得分:-1)

由于您不想全局定义变量,因此您可以使用OOP概念。数据将包装在对象中。我为你写了一段代码。

class user {

private $conn;
private $result;
function __construct(){
    $conn1 = new mysqli("localhost", "root", "", "siteData");
    $this->setConn($conn1);
}

public function profile_info(){
    $query = "SELECT * FROM users";
    $num = $this->getConn();
    $result = $num->query($query);
    return $result;
}

 function users_overview () {
    $result = $this->profile_info();
    while($row = mysqli_fetch_array($result)){
        //get your result
    }
}
 function setConn($conn1){
    $this->conn = $conn1;
    return $this->conn;
 }

 function getConn(){
    return $this->conn;
 }

}

$temp = new user();

$ TEMP-&GT; users_overview();