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

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

问题描述

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

I am using the entries of a db to fill a row and a column in a table. But I cannot access the SQL returned data twice using mysqli_fetch_array() twice. 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对象本身上循环很多次.

You can simply loop on the mysqli_result object itself many times.

//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.

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

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