Looping through the same query twice

Discussion in 'PHP' started by Crash-test dummy, May 7, 2007.

  1. #1
    I have some code that is trying to produce a list of dynamic navigation buttons (much like the page numbers under a Google search) underneath a list of dynamically retrieved list of urls.

    The problem I have is that both need to use the same data but they cause problems when I do. If change one set of data in either loop, I get an error in the other and vice versa.

    Here's the code:

    <?
    $sql = "SELECT tblBlogRank.idBlog, tblBlogRank.datRank, count(tblBlogRank.sIP) as clicks, tblBlog.blogURL, tblBlog.blogTitle FROM tblBlog LEFT JOIN tblBlogRank ON tblBlog.id = tblBlogRank.idBlog WHERE tblBlogRank.datRank > date_sub(curdate(),interval 24 hour)AND tblBlog.id=tblBlogRank.idBlog GROUP BY tblBlogRank.idBlog, tblBlog.blogURL, tblBlog.blogTitle ORDER BY clicks desc";
    // the third parameter of execute() is optional
    $result = $nav->execute($sql, $db, "mysql");
    // handle the returned result set
    $rows = mysql_num_rows($result);
    for ($y = 0; $y < $rows; $y++) {
       $data = mysql_fetch_object($result);		
      	
      	$row = @mysql_fetch_assoc($sql);
    	// Using $result twice is the problem. This needs to be fixed somehow
    		
    	$i++;
    	if ($row['clicks']>1) {
    		echo $i . " <a href=blog_clicks.php?id=" . $row['blogURL'] . " target='new'>" . $row['blogTitle'] . "</a> [" . $row['clicks'] . " visits] <br />";
    		
    	} else {
     		echo $i . " <a href=blog_clicks.php?id=" . $row['blogURL'] . " target='new'>" . $row['blogTitle'] . "</a> [" . $row['clicks'] . " visit] <br />";	
    		
       	}
    }
    echo "<hr>\n";
    // build the returned array of navigation links
    $links = $nav->getlinks("all", "on");
    for ($y = 0; $y < count($links); $y++) {
    
    	
      echo $links[$y] . "&nbsp;&nbsp;";
    	
    }		
    ?>
    PHP:
    Any ideas would be greatly appreciated.
     
    Crash-test dummy, May 7, 2007 IP
  2. bibel

    bibel Active Member

    Messages:
    289
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    58
    #2
    I think you mean $row = @mysql_fetch_assoc($result);

    Every time you use mysql_fetch_{something} you will get the next row of results, so you will go trough all the query results when $y=$rows/2;

    Just comment this line : $data = mysql_fetch_object($result); , because i don't see it being used anyway.
     
    bibel, May 7, 2007 IP