在函数之外返回mysqli结果

时间:2015-03-10 15:15:49

标签: php

给出以下代码:

function fetchData($mysqli){
    $sql = "select * from `test`";
    $result = mysqli_query($mysqli,$sql);
    return $result;
}

$result = fetchData($mysqli);

while($row = mysqli_fetch_array($result)){
    echo $row['id'];
}

我的代码显然比这更复杂。它循环自身,直到它产生一些结果,在每次迭代时改变一些变量。

$结果为空。我究竟做错了什么?谢谢!

完整代码:

function fetchItem($itemID, $period, $mysqli){

    $periodArray = array('7', '30', '60', '90', '180');

    while (current($periodArray) !== $period) next($periodArray);

    $currentPeriod = current($periodArray);

    $sql = "SELECT * from `test` where `period` = '$period'";

    $result = mysqli_query($mysqli,$sql);
    $row_count = $result->num_rows;             

    if($row_count < 5){

        $currentPeriod = next($periodArray);
        fetchItem($itemID, $currentPeriod, $mysqli);

    } else if($row_count >= 5){

        $currentPeriod = current($periodArray);

        $rows = array();

        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }

        // var_dump($rows); <-- returns all results

        return $rows;

    }

}

$output = fetchItem($itemID, $period, $mysqli);

echo '<pre>';
print_r($output); <-- NULL
echo '</pre>';

正如你所看到的,如果我在一段时间内没有得到结果,那就转移到下一个结果。

1 个答案:

答案 0 :(得分:1)

您的代码应为:

function fetchData($mysqli){
   $sql = "select * from `test`";
   $init = mysqli_query($mysqli, $sql);
   $result = $init->fetch_array(MYSQLI_ASSOC);

   return $result;
}

$result = fetchData($mysqli);

foreach($result as $row){
    echo $row['id'];
}