如何使用 mysqli_fetch_array() 两次? [英] How can I use mysqli_fetch_array() twice?

查看:32
本文介绍了如何使用 mysqli_fetch_array() 两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用数据库中的条目来填充表中的一行和一列.但是我无法使用 mysqli_fetch_array() 两次访问 SQL 返回的数据.我需要多次循环 mysqli 结果.这不起作用:

I am using the entries from a database to fill a row and a column in a table. But I cannot access the SQL returned data twice using mysqli_fetch_array() twice. I need to loop mysqli result more than once. This doesn't work:

//Copy the result
$db_res = mysqli_query( $db_link, $sql );
$db_res2=$db_res;

//Top row
while ($row = mysqli_fetch_array( $db_res, MYSQL_ASSOC))
{
        echo "<td>". $row['Title'] . "</td>";
}

//leftmost column
while ($row = mysqli_fetch_array( $db_res2, MYSQL_ASSOC))
{
                    echo "<tr>";
        echo "<td>". $row['Title'] . "</td>";
                    .....
                    echo "</tr>";
}

如何对同一个结果应用两次 mysqli_fetch_array?

How can I apply mysqli_fetch_array twice on the same result?

推荐答案

你不需要 while 循环,也不需要使用 mysqli_fetch_array()根本没有!

You don't need the while loop and you don't need to use mysqli_fetch_array() at all!

您可以简单地在 mysqli_result 对象本身上循环多次.它实现了 Traversable 接口,允许它在 foreach 中使用.

You can simply loop on the mysqli_result object itself many times. It implements Traversable interface that allows it to be used in foreach.

//Top row
foreach($db_res as $row) {
    echo "<td>". $row['Title'] . "</td>";
}

//leftmost column
foreach($db_res as $row) {
    echo "<tr>";
    echo "<td>". $row['Title'] . "</td>";
    .....
    echo "</tr>";
}

但是,您应该将数据库逻辑与显示逻辑分开,为此最好在数据库逻辑中使用 fetch_all(MYSQLI_ASSOC) 将所有记录检索到数组中.

However, you should separate your DB logic from your display logic and to achieve this it is best to use fetch_all(MYSQLI_ASSOC) in your DB logic to retrieve all records into an array.

如果您将所有数据提取到一个数组中,则可以根据需要多次循环该数组.

If you fetch all the data into an array, you can loop that array as many times as you want.

$data = $db_res->fetch_all(MYSQLI_ASSOC);

foreach($data as $row) {
    // logic here...
}

这篇关于如何使用 mysqli_fetch_array() 两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆