Add a </tr> <tr> during a php query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • monion
    New Member
    • Sep 2009
    • 18

    Add a </tr> <tr> during a php query

    All,
    One more question (never ending right???)

    If I have a list of names to pull from (Mitch, Bob, Randy, Simon, Paul & Will)
    in a MYSQL database. How can I query them into a web page using select * from XXXXXX and display them 3 per line?

    Ex:
    Mitch Bob Randy (on one line)
    Simon Paul Will (on the next) and so on and so on?

    I can only seem to list them vertically top down, not conditionally across on multiple lines.

    Thanks in advance,
    MO
  • ssnaik84
    New Member
    • Aug 2009
    • 149

    #2
    well... it depends upon your style of coding.. simplest is..

    Code:
    $sql = "SELECT * FROM tablename";
    $result = mysql_query($sql);
    
    $i=0;
    echo "<table><tr>";
    
    while ($row = mysql_fetch_assoc($result)) {
    
       if($i < 3)
        {
          $i++;
          echo "<td>".$row["columname"]."</td>";
        }
       else
        {
           $i = 0;
           echo "</tr><tr>";
        }
    }
    
    echo "</tr></table>";

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      Originally posted by ssnaik84
      well... it depends upon your style of coding.. simplest is..
      I can imagine something even simpler… if you get the complete result set as array, it’ll be a piece of cake.

      Comment

      • Atli
        Recognized Expert Expert
        • Nov 2006
        • 5062

        #4
        Hey.

        Consider this:
        Code:
        echo "<table><tr>";
        for($i = 0; $row = mysql_fetch_assoc($result); ++$i)
        {
        	if($i % 3 == 0 && $i != 0) 
        	{
        		echo "</tr><tr>";
        	}
        	echo "<td>{$row['item']}</td>";
        }
        for(; $i % 3 != 0; ++$i) 
        {
        	echo "<td>&nbsp;</td>";
        }
        echo "</tr></table>";
        Check out the for loop, and Arithmetic Operators in the manual.
        Last edited by Atli; Sep 27 '09, 06:13 AM. Reason: Added some detail to the code.

        Comment

        • Markus
          Recognized Expert Expert
          • Jun 2007
          • 6092

          #5
          I had this issue once, and our once active expert pbmods gave an elegant solution: http://bytes.com/topic/php/answers/7...ple-strings-tr

          Comment

          Working...