Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to fetch same data multiple times in a page?

Tags:

php

mysql

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

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.

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.

So my questions are:

  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?

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

like image 687
Aajahid Avatar asked Jul 08 '11 23:07

Aajahid


2 Answers

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>';
like image 87
Calvin Davis Avatar answered Oct 20 '22 19:10

Calvin Davis


Just make a reference to it :)

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

// header 
echo $menu;


// footer
echo $menu;
like image 43
AlienWebguy Avatar answered Oct 20 '22 19:10

AlienWebguy