在页面中多次获取相同数据的最佳方法是什么? [英] What is the best way to fetch same data multiple times in a page?

查看:67
本文介绍了在页面中多次获取相同数据的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在从MySQL多次提取数据的页面中显示相同的数据.

I want to show the same data in a page where the data was fetched from MySQL multiple times.

首先,我想在while循环中使用mysql_fetch_assoc()从MySQL获取数据,然后将其显示为菜单.我第二次要在页脚中显示与站点地图相同的数据.

First I want to get data from MySQL using mysql_fetch_assoc() in a while loop and then show it as a menu. The second time I want to show the same data as a sitemap in the footer.

我目前两次拨打mysql_fetch_assoc(),如下所示:

I'm currently calling mysql_fetch_assoc() twice, as follows:

// This one is the Menu
echo '<ul class="menu">';
while( $data = mysql_fetch_assoc($query) ) { 
    echo '<li><a href="page.php?id='.$data['id'].'">'.$data['title'].'</a>';
}
echo '</ul>';

// other page contents here

// at the footer - the small sitemap
echo '<ul class="sitemap">';
while( $f_data = mysql_fetch_assoc($query) ) { 
    echo '<li><a href="page.php?id='.$f_data['id'].'">'.$f_data['title'].'</a>';
}
echo '</ul>';

我认为上面的代码可能通过查询两次数据库来使用比所需资源更多的资源.由于页面中有数据,因此再次获取相同的数据会浪费内存,而且不好.

I think the code above might be using more resources than needed by querying the database twice. Since I have the data in the page, to fetch the same data again is wasting memory and not good.

所以我的问题是:

  1. 每次使用mysql_fetch_assoc()时,它是否发送单独的查询并从数据库中获取数据?还是仅从数据库中获取数据一次,然后又在现有数组中循环?

  1. Does it send separate queries and fetch data from the database each time I use mysql_fetch_assoc()? Or is it only fetching data from the database once, and later it just loops through an existing array?

我的情况下最好的解决方案是什么?

What is the best solution in my case?

简而言之-我是否以最佳方式做到这一点?有没有比不浪费内存/资源/时间更好的方法呢?由于这是我要显示两次的相同数据.

Simply - Am I doing this in the best way? Is there any better way to do this, by not wasting memory/resources/time? Since it's the same data I'm showing twice.

推荐答案

您最好的解决方案是将检索到的数据存储在一个数组中,然后您可以随时使用它,而不必对数据库进行更多查询,例如所以:

Your best solution would be to store your retrieved data in an array, which you can then use whenever you want without having to make more queries to your database, like so:

// First we make the query and store the rows in an array
$result = mysql_query($query);
$data_array = array();
while ($data = mysql_fetch_assoc($result)) {
    $data_array[] = $data;
}

// Then we can loop through the values in that array without making further queries
echo '<ul class="menu">';
foreach ($data_array as $data) {
    echo '<li><a href="page.php?id=', $data['id'], '">', $data['title'], '</a>';
}
echo '</ul>';

// Another loop through our array
echo '<ul class="sitemap">';
foreach ($data_array as $f_data) {
    echo '<li><a href="page.php?id=', $f_data['id'], '">', $f_data['title'], '</a>';
}
echo '</ul>';

这篇关于在页面中多次获取相同数据的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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