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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.