tags:

views:

269

answers:

5

I have similar scripts to this running perfectly well. When i take out the while loop it runs fine (evidently) but everytime i try to get something out of the db it takes forever and then mozilla gives me a download box. I am totally flummoxed so any help would be much appreciated:

include("conn.php");
$result = mysql_query("SELECT * FROM table");

while($row = mysql_num_rows($result));
{
 echo $row['name'];
}
+10  A: 

uh oh..

include("conn.php");
$result = mysql_query("SELECT * FROM table");

while($row = mysql_fetch_assoc($result))
{
        echo $row['name'];
}

edit:

umm.. since this is clearly a matter of syntax error, there is really not much to explain..

  1. a while ended with ; is never a good thing :-s
  2. use mysql_fetch_* (assoc, row, array) for fetching (taking) records from the database
  3. use $total_rows = mysql_num_rows($result); to get the number of rows affected/returned from your query.

lastly, learning by making mistakes is by no means idiot :)

andyk
a bit of an explenation would be nice
hop
mysql_num_rows vs mysql_fetch_assocThe op's code was an infinite loop.
Stefan Mai
@hop Thanks, believe me, I've tried to, but no explanation seems to come to mind. I've added some note now, hopefully that would help op more.
andyk
perfect, i'd say!
hop
+2  A: 

That's pretty much an infinte loop you've got there, I'd guess what you meant to do was:

while($row = mysql_fetch_array($result))
{
        echo $row['name'];
}

So, fetch_array instead of num_rows which will return the same number over and over again.

grapefrukt
you still have the ; between while() and its body
hop
ouch! can't believe i fell for that, that's what you get for trying to be the first to answer ;)
grapefrukt
A: 

If you look at the reference docs for mysql_num_rows you'll see that it returns the number of rows in the result set from your query. It doesn't change each time you call it, and so your while-loop doesn't terminate.

What you want is something like:

$n = mysql_num_rows($result);
while ( $n > 0 ) {
    // ...
    --$n;
}

You can also use mysql_fetch_array or mysql_fetch_assoc

csl
+1  A: 

Thanks guys. I am apparently an idiot!

Drew
Been there done that. Have the t-shirt, mug, key chain, towels, beach-ball, sheet set, and a whole closet full of other assorted items.
Unkwntech
No, you're absolutely not! This is how you learn. Keep coding! :)
csl
don't post this as an answer. accept the answer you like.
hop
A: 

everytime i try to get something out of the db it takes forever

Also, if in your original query you are selecting everything from table (*), consider selecting only the fields you need, it should work faster.

ya23