Necesito ayuda para la lógica ilógica en tablas PHP + mysql y HTML

New to this board but loving it so far :)

I am currently helping a friend of mine redo her personal website and I am running my head against a wall on the logic for a table.

The table is suppossed to show the latest news in a table consisting of 4 columens/cells/TDs pr row (nothing more) - looing something like this: http://screencast.com/t/Rh39oh6ms0OL

So basically I have a SQL query that selects the date, thumbnail and headline from the news table (ordered by id desc so I get the newest first).

I have made some logic (as you can see in the code below) but it is only resulting in the first row of the table showing. Anyone out there who can get me back on the right track? It will be very much appreciated.

<table>
  <?php
  //PHP code used for building HTML table showing news-resumes
  //Written by:  Jesper Flindt
  //Date:       2012.07.30
  //Version:   1.0

  //Getting data from MySQL database
  $query  = "select date, thumbnail, headline from news order by id desc";
  $result = mysql_query($query) or die("Connection Error:" . mysql_error());

  //Setting variables
  $i   = 0;
  $p  = 0;

  //Starting row in table
  print('<tr>');

  //Looping through the resultset
  while($row = mysql_fetch_assoc($result))
  {
    //Limit row to 4 cells (TDs)
    if($i < 4)
    {
      //Display the date of the news as well as its thumbnail
      print('<td><div style="padding-left:8px;"><b>Tilf&oslash;jet d. '.$row['date'].'</b></div><div class="news_thumbframe"><img src="./upload/'.$row['thumbnail'].'" alt=""/></div></td>');
      $i++;
      $p++;
    }
    //If row is 4 cells wide, start new row
    else if($i % 4 == 0)
    {
      print('</tr><tr>');
      $i++;
      $p++;
    }
    //Every second row should display the news headline as well as a "Read More" link ("L&aelig;s mere" in danish)
    else if($i % 4 != 0 || $p % 4 == 0)
    {
      print('<td width="215" valign="top"><br /><div style="padding-left:8px;"><h2>'.$row['headline'].'</h2><a href="#">L&aelig;s mere</a></div></td>');
      $i++;
      $p++;
    }
    else
    {
      $i = 0;
      $p = 0;
    }
  }
  ?>
</table>

preguntado el 31 de julio de 12 a las 12:07

Estoy asumiendo $p is $i's younger brother and just copying everything $i does because he thinks he's cool. -

The MySQL functions should no longer be used. Instead use MySQLi or PDO to access your database. -

Are u trying to put image1 n date1 at row1,col1(of html table) & headline1 at row2,col1 at first execution of the loop ?? -

@Lusitanian While I completely agree, I think it's more important to address the fundamental logical issues. Even though this style of coding is not to be encouraged, one should be able to produce the correct result with it. -

@phant0m hence why my remark was a comment rather than an answer -

3 Respuestas

For every result (that is one toda news entry, not a column of one), you execute exactly one of your if clauses, because you use an if/elseif/elseif/else construct. They are mutually exclusive.

Implicación:

This skips every fourth row of your database result altogether:

else if($i % 4 == 0)
{
  print('</tr><tr>');
  $i++;
  $p++;
}

This captures all rows that are not multiples of 4 and greater than 4:

else if($i % 4 != 0 || $p % 4 == 0)
    {
      print('<td width="215" valign="top"><br /><div style="padding-left:8px;"><h2>'.$row['headline'].'</h2><a href="#">L&aelig;s mere</a></div></td>');
      $i++;
      $p++;
    }

This will never execute:

else
{
  $i = 0;
  $p = 0;
}

because your other conditions already exhaust all possibilities.

  • The first clause will execute 4 times.
  • Then the second clause will execute once, because $i == 4.
  • Now the third clause will execute for $i == 5, 6, 7
  • The second clause will execute for $i == 8
  • The third clause will execute for $i == 9, 10, 11

etc etc

Why do you have two counter variables? As far as I can see, you always increment them at the same places, and set them to zero at the same places. What's the difference?

Noticias

To clarify something you mentioned in the comment:

else if($i % 4 != 0 || $p % 4 == 0)

|| denotes a logical or. It will first check the first condition, when that isn't true, it will check the second condition. If any of them is true, the entire condition is considered true, and the clause will execute.

Sin embargo, $i % 4 != 0 is only false, when $i % 4 == 0 is true. This means, that the previous else if clause executed. The check never even gets to the $p parte.

Respondido 31 Jul 12, 13:07

Ok thanks... I'll get it a new try with you comment in mind but note that in the second clause it is else if($i % 4 != 0 || $p % 4 == 0) - that clause uses $i for the first part and $p for the second part and NOT $i for both - JFlindt

@JFlindt: The second part || $p % 5 == 0 is never true and never executed. - fantasma

@JFlindt I updated my question to better explain why it's not important. Have a look at the end. - fantasma

@phant0m Thanks for your input ... it's been ages since I've had to do some programming so I'm a bit rusty. - JFlindt

may be looks better

$result = mysql_query($query) or die("Connection Error:" . mysql_error());

$items = array();

while($row = mysql_fetch_assoc($result)){
   $items[] = array('date'=>$row['data'],
                    'thumbnail'=>$row['thumbnail'],
                    'headline'=>$row['headline'],);
}

$pairs = array_chunk($items,4);

foreach ($pairs as $pair){

  print '<tr>';

  foreach ($pair as $row){
    print('<td><div style="padding-left:8px;"><b>Tilf&oslash;jet d. '.$row['date'].'</b></div><div class="news_thumbframe"><img src="./upload/'.$row['thumbnail'].'" alt=""/></div></td>');
  }

  print '<tr/><tr>';

  foreach ($pair as $row){
    print('<td width="215" valign="top"><br /><div style="padding-left:8px;"><h2>'.$row['headline'].'</h2><a href="#">L&aelig;s mere</a></div></td>');

  }  
  print '<tr/>'; 
}

Respondido 31 Jul 12, 13:07

@voodoo417 - thanks for you help - this solution did the trick for me. Now to analyze your code example so I'll have the right tools in my head the next time I need it. - JFlindt

You can modify the code , so you can generate both [thumbnail,date] & [headline] together every 4 sets

PHP:

  //Setting variables
  $i   = 1;
  $img_date = '';  
  $headline =''; 

  //Looping through the resultset
  while($row = mysql_fetch_assoc($result))
  {
     //Building both  content for 4 columns
     $img_date .= '<td><div style="padding-left:8px;"><b>Tilf&oslash;jet d. '.$row['date'].'</b></div><div class="news_thumbframe"><img src="./upload/'.$row['thumbnail'].'" alt=""/></div></td>';

    $headline .='<td width="215" valign="top"><br /><div style="padding-left:8px;"><h2>'.$row['headline'].'</h2><a href="#">L&aelig;s mere</a></div></td>';


     if($i == 4) // Time build row
     {  
        // Building both thumbnail and headline row 
        echo "<tr id='thumb_date'>$img_date</tr>";
        echo "<tr id='headline'>$headline </tr>";

         //resetting  
        $i=1; 
        $img_date = '';  
        $headline ='';
      }
      else
        i++;

   }//end while

Respondido 31 Jul 12, 13:07

Nice input @Makesh however voodoo417's solution did the trick. - JFlindt

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.