我想在从 MySQL 多次获取数据的页面中显示相同的数据。
首先,我想在 while 循环中使用 mysql_fetch_assoc()
从 MySQL 获取数据,然后将其显示为菜单。第二次我想在页脚中显示与站点地图相同的数据。
我目前正在调用 mysql_fetch_assoc()
两次,如下所示:
// 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>';
我认为上面的代码可能使用了比查询数据库两次所需的更多的资源。由于我在页面中有数据,再次获取相同的数据是浪费内存而且不好。
所以我的问题是:
每次我使用
mysql_fetch_assoc()
时,它是否会发送单独的查询并从数据库中获取数据?或者它只是从数据库中获取数据一次,然后它只是循环遍历一个现有的数组?我的情况下最好的解决方案是什么?
简单地说——我这样做的方式是否最好?通过不浪费内存/资源/时间,有没有更好的方法来做到这一点?因为这是相同的数据,所以我显示了两次。
最佳答案
您最好的解决方案是将检索到的数据存储在一个数组中,然后您可以随时使用该数组,而无需对数据库进行更多查询,如下所示:
// 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>';
关于php - 在页面中多次获取相同数据的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6631573/