我想在多次从 MySQL 获取数据的页面中显示相同的数据。
首先我想使用MySQL从MySQL获取数据mysql_fetch_assoc()
在 while 循环中,然后将其显示为菜单。第二次我想在页脚中显示与站点地图相同的数据。
我现在正在打电话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>';
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)