How to reuse the same query on the page

I have added my first php page to add a dynamic page but need to display the results of a my sql query in different sections.

For a menu to link to its own page and display a summary of each seperatly on the page.

<?php
$query
= mysql_query("SELECT * FROM descriptions");
while (
$row=mysql_fetch_array($query)){
  print
'<a href='more.php?id=' . $row['id'] . '">' . $row['name'] . '</a><br />';
}

?>

Down lower on the page loop through again but had to requery seems a waste although it loads still pretty fast I'm the only one viewing the page think it will go slow with more visitors.
$query = mysql_query("SELECT * FROM descriptions");
while ($row=mysql_fetch_array($query)){
  print '<a href='more.php?id=' . $row['id'] . '">' . $row['name'] . '</a><br />';
  print '<p>' . $row['summary'] . '</p>';
}

?>

D

No votes yet

Replies

Use mysql_data_seek or arrays

You could reset the query using mysql_data_seek

The second query set the query object back to row 0

<?php
mysql_data_seek
($query  , 0);
while (
$row=mysql_fetch_array($query)){
  print
'<a href='more.php?id=' . $row['id'] . '">' . $row['name'] . '</a><br />';
  print '<p>' . $row['summary'] . '</p>';
}
?>

Or if you find yourself needing different parts of the results through out the page store it in an array

First query

<?php
$query
= mysql_query("SELECT * FROM descriptions");
$data = array();
while (
$row=mysql_fetch_array($query)){
 
//you can come up with various ways to store it
  //depending on what you need
 
$data[]['id'] = $row['id'];
 
$data[]['name'] = $row['name'];
 
$data[]['summary'] = $row['summary'];
  print
'<a href='more.php?id=' . $row['id'] . '">' . $row['name'] . '</a><br />';
}
var_dump($data);//just to see what and how it stored
?>

Your rating: None

Post new comment

 
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><code>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.