tags:

views:

208

answers:

3

Hello, I have some code that works, but is clunky and am wondering if there is a better way to do it, first the code, and then i will explain:

// repeat query 10 times
for ($i = 1; $i <= 10; $i++) {
   $query = @mysql_query("SELECT fileName FROM images");
    while($row = mysql_fetch_assoc($query)){
     extract($row);
     echo "<img src='images/images/$fileName'/>";
    }
}

I would like to repeat a set of images whose file names are stored in a mySql table. The code above repeats the query 10 times. I would rather query once, then repeat the list. Is there a way to do this, either on the mySql side or in the php loop?

Thanks.

+3  A: 

Cache all the rows from the query in an array. Loop through the cache array 10 times and print.

$a= array();
$query= mysql_query("SELECT fileName FROM images");
while($row = mysql_fetch_assoc($query))
 $a[]= $row;

for ($i = 1; $i <= 10; $i++) {
 foreach ($a as $row)
   echo "<img src='images/images/{$row['fileName']}'/>";
}

Of course you'll need to sanitize the output of $row['fileName']

pygorex1
I have not yet heard of sanitizing the outputs
superUntitled
sanitizing in this case would be something like `printf('<img src="images/%s" />', htmlentities($row['fileName']));`
pygorex1
+3  A: 

Use mysql_data_seek()

$rs = mysql_query("SELECT * FROM item_user");
for($i = 1; $i <= 10; $i++)
{
    echo "$i\n";
    while(false !== ($r = mysql_fetch_array($rs)))
    {
     echo "  $r[0]\n";
    }
    mysql_data_seek($rs, 0);
}
silent
Cool. Did not know about mysql_data_seek
pygorex1
well, you should consider php manual as your second bible!
silent
I refer to it daily - but one tends to get stuck in a rut when they've already figured out a problem.
pygorex1
+1  A: 

Here's a much nicer way than hitting your Database 10 times.

//declare an array
$imageArray = array();

// repeat query 10 times
for ($i = 1; $i <= 10; $i++) {
   $query = @mysql_query("SELECT fileName FROM images");
    while($row = mysql_fetch_assoc($query)){
        extract($row);
        $imageArray[] = $fileName; //sequentially add each row to the array
    }
}
//loop over the array
//At this stage you can use the array for whatever you like. Iterating over an array is easy.

foreach ($imageArray as $image){
   echo sprintf('<img src="images/images/%s" />',$image);
}
Jessedc
What kind of programmer loops from 1 to 10? Weird. I'd drop the `extract` function, and use `$imageArray[] = $row['fileName']` instead.
Mark
My solution was attempting to modify the original question's code as little as possible.
Jessedc