Output same set of database results in two locations on a page

Hi everyone,

This is a stupid question, but I just can’t find a solution to it, and I feel like there should just be something really obvious that will do it.

Basically, I have a very simple table. What I want to do with this table is return all the rows, and output the data to two different places on my page - one an unordered list, as a menu; the other my main content area, where the same results will appear with a little thumbnail pic, etc.

There’s obviously got to be a better way of doing this than performing the same query twice, but all I can think of is to add the details to a new array inside the first while loop - and that doesn’t seem like a very elegant solution either.

Any help on this would be appreciated. I’ve tried searching but I just can’t even think how to phrase it to get meaningful results!

The way that you suggest seems fine to me - i.e. put them in an array in the first loop.

Possibly more elegant, would be to have one loop at the start, which creates the html required for both, then echo each in the appropriate place in your page.

You would store the results from the first query “somewhere” then just reuse them as and when you want, it really depends on your application structure.

Maybe a quick example would help…


<?php
function get_listings()
{
  static $cache = null;
  
  if(null === $cache)
  {
    $sql    = 'SELECT id, title, pic FROM table;';
    $res    = mysql_query($sql);
    $cache  = array();
    
    while($record = mysql_fetch_assoc($res))
    {
      array_push($cache, $record);
    }
  }
  
  return $cache;
}
?>

<ul>
  <?php foreach(get_listings() as $listing): ?>
    <li><?php echo $listing['title']; ?></li>
  <?php endforeach; ?>
</ul>

<div id="gallery">
  <?php foreach(get_listings() as $listing): ?>
    <img src="<?php echo $listing['pic']; ?>" alt="<?php echo $listing['title']; ?>" />
  <?php endforeach; ?>
</div>

This may not work as I have posted it, but I recall doing this for complex menus etc.


$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
    die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);

foreach( $result as $row1 ){
// output once

}

You should be able to reset the result and loop again…


reset($result);

foreach( $result as $row2 ){
// output again

}

This is also useful when used in conjunction with PHP: mysql_data_seek - Manual instead of reset

Thanks guys, your input is appreciated. Good to see that I was at least on the right track with my thoughts on the matter!