Jump to content

[SOLVED] Foreach and While Inside Each Other Doesn't Work?


Recommended Posts

Hello all!

 

Apologies for having a newb question, but the following script only outputs one ID , when it should output multiple IDs

<?

$userfile= file_get_contents("file.txt");
$urls = explode("\n",$userfile);

foreach ($urls as $url) {


$result = mysql_query("SELECT * FROM url WHERE website='$url'") 
or die(mysql_error());  


while($row = mysql_fetch_array( $result )) 
{

	echo $row['id'];

}

}


?>

 

 

 

 

Thanks in advance!

Maybe the file only has one row... as a nicer way to do this, might I suggest the following code?

 

<?php

$userfile= file("file.txt",FILE_IGNORE_NEW_LINES |   FILE_SKIP_EMPTY_LINES);

foreach ($userfile as $line) {
$line = mysql_real_escape_string($line);//it might be nice to escape it :-) if this is a file you control, don't need to, but if it's stuff other users add in, might be helpful for preventing against sql injection

   $result = mysql_query("SELECT * FROM url WHERE website='$line'")
   or die(mysql_error()); 


   while($row = mysql_fetch_array( $result ))
   {

      echo $row['id'];

   }

}


?>

Ah, now it works. I think it was because I had

 

    echo (something invalid);

    echo $row['id'];

 

Thanks for helping me out! I really appreciate it.

 

edit:Right now, i'm at a complete loss.

 

 

  while($row = mysql_fetch_array( $result ))
   {

      echo $row['id'];

   }

 

Then I added:

 

echo "<iframe src=\"";

 

above the

    echo $row['id'];

 

It only outputs one ID. (I know I should concatenate the string, but this makes it easier for me to see)

 

If I add

echo "a";

 

above

 

    echo $row['id'];

 

it works just fine.

 

Thanks in advance.

 

It's because you need to close your iframe with </iframe>

 

<iframe src="<?=$id?>">
      <?

 

Think of the open iframe tag like a textarea. Since it isn't being echoed out through PHP but as normal HTML, it's a vacuum for all the code beneath it. In effect, stopping your script short.

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.