Home >Backend Development >PHP Tutorial >关于mysqli_fetch_row一次只能返回一行数组

关于mysqli_fetch_row一次只能返回一行数组

WBOY
WBOYOriginal
2016-06-06 20:36:35966browse

<code>$qst_id = $_GET['str'];
if ($qst_id) {
    $qst_sql = "SELECT * FROM exam_qst WHERE qst_id='$qst_id'";
    $query = $conn -> query($qst_sql);
    $row = $query -> fetch_array();
    $length = sizeof($row)/5;
    $a = 0;
    while ($a ";
        while ( $i$row[$j]";
        }
        echo "";
        $a++;
    }
    $query -> close();  
} 
$conn -> close();
</code>

如代码,每次查询数据库应该取出多行数据,但是mysqli_fetch_array跟mysqli_fetch_row似乎都只能返回一行数据。请问如何能将查询到的所有数据全部装到一个数组里。

回复内容:

<code>$qst_id = $_GET['str'];
if ($qst_id) {
    $qst_sql = "SELECT * FROM exam_qst WHERE qst_id='$qst_id'";
    $query = $conn -> query($qst_sql);
    $row = $query -> fetch_array();
    $length = sizeof($row)/5;
    $a = 0;
    while ($a ";
        while ( $i$row[$j]";
        }
        echo "";
        $a++;
    }
    $query -> close();  
} 
$conn -> close();
</code>

如代码,每次查询数据库应该取出多行数据,但是mysqli_fetch_array跟mysqli_fetch_row似乎都只能返回一行数据。请问如何能将查询到的所有数据全部装到一个数组里。

<code>$qst_id = $_GET['str'];
if ($qst_id) {
    $qst_sql = "SELECT * FROM exam_qst WHERE qst_id='$qst_id'";
    $query = $conn -> query($qst_sql);
    $row = $query ->fetch_all();
    foreach ($row as $vl){
        echo "<tr>
<td>".$vl[1]."</td>
<td><a onclick="show_more(this)">".$vl[2]."</a></td>
<td>".$vl[5]."</td>
<td>".$vl[4]."</td>
<td>".$vl[6]."</td>
</tr>";
    }
    $query -> close();  
}
</code>

确实是需要遍历所有的结果集,自己用foreach来执行并成功返回了。还是谢谢 @捞鱼的转阿转

话说是mysql__fetch_array和mysql_fetch_row吧。他俩功能差不多,都是已数组的形式返回一行数据。
所以返回一行是没错的。你需要的是遍历所有的结果集,需要通过循环的帮助。

下面的给你参考

<code>php</code><code>    /**
     * 获取执行SQL所有数据
     * @param  [type] $sql 待执行
     * @return [type]      执行返回结果
     */
    public function fetchAll($sql){
        if ($result = $this->query($sql)) {
            $rows = array();
            while ($row = mysql_fetch_row($result)) {
                $rows[ ] = $row;
            }
            mysql_free_result($result);
            return $rows;
        }else{
            return false;
        }
    }
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn