Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHILE loops can't be used twice? PHP

Tags:

html

loops

php

I am new to PHP , I hope someone can help me. I have a table which contains "id" , "img" , "link" and "desc" in mysql database . I want it to echo all out into something like this :

    <div id="featured">
    <a target='_blank' href='link'><img src='image link1' title='description'/></a>
    <a target='_blank' href='link'><img src='image link2' title='description'/></a>
    <a target='_blank' href='link'><img src='image link3' title='description'/></a>
    <a target='_blank' href='link'><img src='image link4' title='description'/></a>
    </div>
    <div id="cap">
    <span class='desc' id='idnumber'>Description1</span>
    <span class='desc' id='idnumber'>Description2</span>
    <span class='desc' id='idnumber'>Description3</span>
    <span class='desc' id='idnumber'>Description4</span>
    </div>

PHP CODE:

<?php
  require_once "./dbconfig.php";
  opendb();
  $sql = "SELECT * FROM images ORDER BY id DESC"; 
  $query = querydb($sql);
?>
<div id="featured"> 
<?php
  while($row = mysql_fetch_array( $query )){
    echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
  }
?>
</div>
<div id="cap">
<?php
  while($row = mysql_fetch_array( $query )){
    echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
  }
closedb();
?>
</div>

Can WHILE being used twice or i am wrong? when i run this code , the second while loop is not working , the spans are not showing at all.

Please help.

like image 223
ETAN Avatar asked Jul 06 '11 09:07

ETAN


2 Answers

The first loop consumes all data from mysql already, so there is nothing left in the second loop. You can store the rows data in the meanwhile however and then re-use that store.

<div id="featured"> 
<?php
$rows = array();
while($row = mysql_fetch_array( $query )){
  $rows[] = $row;
  echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
foreach($rows as $row){
  echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
like image 150
hakre Avatar answered Sep 19 '22 14:09

hakre


Use this before your second while loop

mysql_data_seek($query,0);
like image 30
JConstantine Avatar answered Sep 21 '22 14:09

JConstantine