using foreach to generate list

Discussion in 'PHP' started by mnymkr, Jun 18, 2007.

  1. #1
    I am having a bit of a brain fart here.

    I have used this code in countless joomla modules but for now I can't get my desired result

    
    $result = mysql_query("SELECT title FROM jos_content");
    
    $objects = mysql_fetch_object($result);
    
    
    
    
    //forms list
    
    
    foreach($objects as $row) {
    
    echo "<li>".$row->title."</li>";
    
    }
    
    
    //another way to form list
    
    while($objects = mysql_fetch_object($result)) {
    		echo "<li>".$objects->title."</li>";
    	}
    
    
    Code (markup):
    The foreach part will nto generate a list

    but the second one will

    what is wrong here?
     
    mnymkr, Jun 18, 2007 IP
  2. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #2
    mysql_fetch_object() gets an object then advances the pointer to the next result set. So calling it next time will get the next result.

    In the first one, you are setting $objects to the first result. Maybe if you renamed $objects to $object as it should be, it would make more sense.
     
    krt, Jun 18, 2007 IP
  3. mnymkr

    mnymkr Well-Known Member

    Messages:
    2,328
    Likes Received:
    32
    Best Answers:
    0
    Trophy Points:
    120
    #3
    I am not quite sure I understand. I will tell you why. I started learning code in Joomla and I have used this so many times to produce a list. So I am not quite seeing what you are talking about


    How could I use foreach correctly to make a list in the case? or can I?

    Thanks for responding
     
    mnymkr, Jun 18, 2007 IP
  4. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #4
    Here is why it doesn't work. Note I use $object because we are fetching an object, not multiple objects.
    $object = mysql_fetch_object($result);
    
    foreach($object as $row) {
        echo "<li>".$row->title."</li>";
    }
    PHP:
    $object is singular, so there is only one element for foreach() to loop over.
     
    krt, Jun 18, 2007 IP
  5. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #5
    you have to loop over the original results, doing it like ^^ that will only display the first row of results from the initial sql query, gotta while() over it - to show them all you

    while( $object = mysql_fetch_object( $result ) )
    {
    printf( '<li>%s</li>', $object->title );
    }

    alternatively, if you are addicted to foreach

    while( $object[] = mysql_fetch_object( $result );

    foreach( $object as $row )
    {
    printf( '<li>%s</li>', $row->title );
    }
     
    krakjoe, Jun 18, 2007 IP