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

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
<?phpmysql_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
?>
Post new comment