Jump to content

Database While Loop


Omzy

Recommended Posts

This is probably really easy but it's been a while since I touched PHP, so any advice would be appreciated. Basically what I want to do is output dynamic data from the database:

 

$query="SELECT * FROM products WHERE cat_id=$cat_id AND";
$results = mysql_query($query);
$numrows = mysql_num_rows($results);

while($row=mysql_fetch_assoc($results))
{
  $prod_id=$row['prod_id'];
  $name=$row['name'];
}

echo "<script language="javascript"> ";
echo "var i=0; ";
echo "var roll_images=new Array; ";
for($i=0;$i<$numrows;$i++)
{
  $array[$i]=$prod_id;
}
for($i=0;$i<$numrows;$i++)
{
  echo "roll_images[".$i."]="images/r/".$array[$i].".jpg"; ";
}
echo "</script> ";

 

This is just a snippet of the code, I've removed most of the stuff so that you get a better idea of what's going on. As you can see I've echo'd the <script> tag outside of the WHILE loop to stop it from being output every time it loop, however I need the internal FOR loop to run within the WHILE loop. How can this be achieved? I cant move the <script> tag above the WHILE loop because I have other scripts that also need to be put in the WHILE loop.

Link to comment
https://forums.phpfreaks.com/topic/176580-database-while-loop/
Share on other sites

Hi

 

Appears to be a complex way to do it, as though you are trying to read everything into an array and then loop through the array.

 

This might be simpler

 

echo "<script language="javascript"> ";
echo "var i=0; ";
echo "var roll_images=new Array; ";

$query="SELECT * FROM products WHERE cat_id=$cat_id AND";
$results = mysql_query($query);
$i=0;
while($row=mysql_fetch_assoc($results))
{
echo "roll_images[".$i."]="images/r/".$row['prod_id'].".jpg"; ";
$i++;
}
echo "</script> ";

 

All the best

 

Keith

Link to comment
https://forums.phpfreaks.com/topic/176580-database-while-loop/#findComment-930904
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.