Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm very new to web programming, and I'm working through a Vikram Vaswani's How to Do Everything With PHP and MySQL. Near the end, he shows how to do a web program which shows news items and allows the user to edit and add different news items. The code doesn't seem to work and I've tweaked it to get it to work, but I'm still confused. In particular, I have the following code (this website isn't handling the breaks very well)

// if records present
if (mysql_num_rows($result) > 0)
{
    // iterate through resultset
    // print article titles
    while($row == mysql_fetch_object($result));
    {
    ?>
        <li><a href="story.php?Ticker=<?php echo $row->Ticker;?>"><?php echo $row->StockName;?></a></li>
        <?php 
        $row = mysql_fetch_object($result);  
        echo $row->Ticker;
        echo $row->StockName;

<br>

Now, the book had while ($row = mysql_fetch_object($result)); - but that didn't do anything. So I changed it to an equal comparison operator. I'm thinking that with the $row = mysql_fetch_object($result) at the bottom in the loop, it should move onto the next row of the table since this is the normal behavior per http://us2.php.net/manual/en/function.mysql-fetch-object.php and per my own testing. I can do this differently with a for loop or something but I would like to figure out why it isn't working how I expect here.

share|improve this question
If while ($row = mysql_fetch_object($result)); did not work for you, then $row = mysql_fetch_object($result); won't do either. Using == is not correct in this case. What is your actual question? – Felix Kling Mar 7 '11 at 0:24
up vote 0 down vote accepted

It should definitely be:

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

}

It looks like you've got a semicolon at the end of the while line, and that would end the while loop right then. Instead you should be opening up a block of code with parenthesis. If no results are returned, then it will be false and exit the while loop.

share|improve this answer
Wow, thanks - that was the problem. It works as expected now. That little mistake was screwing with my head. – cluelesscoder Mar 7 '11 at 3:20

In your while loop, the mysql_fetch_object() returns the next row in your $result. If you're testing with == operator it cannot be true.

share|improve this answer
Basically, if(null == object) (which it will not be) then exit the while loop (that contains an empty statement). – Forest Ka May 9 at 6:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.