PHP query and repeat mysql_fetch_array
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.
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']
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);
}
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);
}
精彩评论