Forum Moderators: coopster

Message Too Old, No Replies

while() loop not working.

         

smatts9

7:40 pm on Aug 25, 2006 (gmt 0)

10+ Year Member



Here is the code


<?
include('db.php');
$result=mysql_query("SELECT * FROM cities");
if($result) {
while($cities=mysql_fetch_object($result))
{
$city = $cities -> city;
$state = $cities -> state;

$url = "http://url.com/$state/$city";
$data = file_get_contents($url);
$result=eregi('</strong></div>(.*)<HR>', $data, $match);
$pattern = '#<a href=([^>]+)>#i';
preg_match_all($pattern, $data, $results);
echo "<pre>results "; print_r($results[1]); echo "</pre>";

foreach ($results[1] as $url) {
if (eregi('\"', $url)) {
echo "ignored";
echo "<br />";
} else {

$short=$state;
$sql = "INSERT INTO urls (state, url) VALUES('$short', '$url')";
mysql_query( $sql );
echo $url;
echo " entered";
echo "<br />";
}
}
}
}

?>

The script will go fetch the first row from the cities table, and go through the while and foreach loops and input the info into the urls table.

When the while loop goes back for the second loop using the second row from the cities db it fails. The table has 6000 and some rows, so it isnt empty or anything.

I get this error:


Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in file.php on line 5

Thank you.

eelixduppy

8:07 pm on Aug 25, 2006 (gmt 0)



Your query isn't working properly. Try changing this line:

$result=mysql_query("SELECT * FROM cities");

To something like this:


$result=mysql_query("SELECT * FROM cities") or [url=http://us2.php.net/manual/en/function.die.php]die[/url]([url=http://us2.php.net/mysql_error]mysql_error[/url]());

Good luck!

smatts9

8:12 pm on Aug 25, 2006 (gmt 0)

10+ Year Member



It gives me no error?... Just the same thing as before.

dreamcatcher

8:26 pm on Aug 25, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



When you echo mysql_num_rows($result) what does it give you?

dc

smatts9

10:07 pm on Aug 25, 2006 (gmt 0)

10+ Year Member



I figured it out. I had defined $result twice and it would stop the loop.

eelixduppy

10:09 pm on Aug 25, 2006 (gmt 0)



Nice catch! I wasn't thinking along those lines, but I'm glad you found it ;)