Insert <tr> at intervals

EE,
I am using PHP to extract data from a mysql database to write out static html web pages.
I am writing out a long table and I would like to insert </tr><tr> after every third record.
I tried using:
if($i % 3 == 1)
{
               fwrite( $out,"</tr><tr>" ) ;
}

but it is not working.

Any suggestions?

Any help would be greatly appreciated.
dresdena1
dresdena1Asked:
Who is Participating?
 
Michel PlungjanIT ExpertCommented:
Move the $i=0 outside the loop and use %0 instead of %1

E.g. Change line 21 and 32 here

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



      $id = $row["id"] ;
      $url = $row["url"] ;
      $img = $row["img"] ;
      $img_width = $row["img_width"] ;
      $img_height = $row["img_height"] ;
      $sm_img = $row["sm_img"] ;
      $sm_width = $row["sm_width"] ;
      $sm_height = $row["sm_height"] ;
      $category = $row["category"] ;
      $H1 = $row["H1"] ;


      //print a table row.

  // Pass make the request.

$i = 0 ;

       fwrite( $out,"\n\n" ) ;
 fwrite( $out,"<td align=center>" ) ;
// fwrite( $out,"<a href=\"$url.html\"><img src=\"http://www.abc123.com/$sm_img\" width=\"$sm_width\" height=\"$sm_height\" class=\"borderimg\"></a>" ) ;
 fwrite( $out,"<a href=\"chargerrt/$img\" rel=\"prettyPhoto[pp_gal]\" title=\"$H1\"><img src=\"chargerrt/$sm_img\" class=\"picthumb\" width=\"150\" height=\"150\" alt=\"$H1\" /></a>" ) ;

//       fwrite( $out,"<BR>$date" ) ;
       fwrite( $out,"</td>" ) ;


if($i % 3 == 1)
{
       fwrite( $out,"</tr><tr>" ) ;
}



      $i++ ;



    }

Open in new window

to
$i = 0 ; // initialise counter
while ($row = mysql_fetch_assoc($result)) {



      $id = $row["id"] ;
      $url = $row["url"] ;
      $img = $row["img"] ;
      $img_width = $row["img_width"] ;
      $img_height = $row["img_height"] ;
      $sm_img = $row["sm_img"] ;
      $sm_width = $row["sm_width"] ;
      $sm_height = $row["sm_height"] ;
      $category = $row["category"] ;
      $H1 = $row["H1"] ;


      //print a table row.

  // Pass make the request.

       fwrite( $out,"\n\n" ) ;
 fwrite( $out,"<td align=center>" ) ;
// fwrite( $out,"<a href=\"$url.html\"><img src=\"http://www.abc123.com/$sm_img\" width=\"$sm_width\" height=\"$sm_height\" class=\"borderimg\"></a>" ) ;
 fwrite( $out,"<a href=\"chargerrt/$img\" rel=\"prettyPhoto[pp_gal]\" title=\"$H1\"><img src=\"chargerrt/$sm_img\" class=\"picthumb\" width=\"150\" height=\"150\" alt=\"$H1\" /></a>" ) ;

//       fwrite( $out,"<BR>$date" ) ;
       fwrite( $out,"</td>" ) ;


if($i > 0 && $i % 3 == 0)
{
       fwrite( $out,"</tr><tr>" ) ;
}



      $i++ ;



    }

Open in new window

0
 
Michel PlungjanIT ExpertCommented:
That would be

if($i % 3 == 0)

if I am not mistaken
0
 
HagayMandelCommented:
$i = 1;
fwrite( $out,"<tr>" ) ;
if ( CONDITION ) {
    // ....

     // if multiple of 3
     if($i % 3 == 0) {fwrite( $out,"</tr><tr>" ) ;}
     $i++;
}
fwrite( $out,"</tr>" ) ;

Open in new window

0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
Michel PlungjanIT ExpertCommented:
That would be simpler written as

if($i > 1 && $i % 3 == 0)
0
 
Ray PaseurCommented:
not working
That does not give us very much to go on.  What, exactly, is wrong?  Have you verified that the query returns at least three rows?  Is the file getting written at all?  Are you using any kind of loop control, such as a for(), foreach() or while() programming structure?  Is the script incrementing the counter?

Please tell us a little more about the symptoms.  You can find out a lot by learning to use var_dump() to visualize the data.

And sometimes the "clever" way of programming gets in the way of progress.  This is how I might write it (pidgin code, but you get the idea, I hope)

$n = 3;

// RETRIEVE EACH ROW FROM THE RESULTS SET
while ($row = mysql_fetch_assoc($res))
{
    // START A ROW IF N==3
    if ($n == 3)
    {
        write TR
    }
    
    // WRITE A DATA ELEMENT AND REDUCE THE COUNTER
    write TD
    write $row
    write /TD
    $n = $n - 1;
    
    // IF THE COUNTER HITS ZERO, CLOSE THE ROW AND RESET THE COUNTER
    if ($n == 0)
    {
        write \TR
        $n = 3;
    }
}

// AT THE END OF THE DATA, FILL OUT THE ROW
if ($n != 3)
{
    while ($n)
    {
        write TD
        write empty-data
        write /TD
        $n = $n - 1;
    }
    write \TR
}

Open in new window

0
 
Michel PlungjanIT ExpertCommented:
Ahem... Ray, I would think that using % to count instead of resetting counters is a recognised pattern and not considered more clever. It does save a lot of logic.
0
 
dresdena1Author Commented:
Thank you for all of the responses.
I have tried the various options listed using modulus but I could not get any of them to work. I have attached the page to this update.
My knowledge of PHP is beginner/advancer beginner (at best).
I used to get help with such things from my old ISP but they have closed their doors.
I have attached the page to this as I read in another comment that that will make it easier / clearer to determine the problem/solution.

With regards to how the page currently works, it creates (writes out) the page, inserts the code for the images, but does not include any </tr><tr> to start new rows. It is as if it does not even see the modulus IF statement.
0
 
Michel PlungjanIT ExpertCommented:
Please attach the page. It was missing
0
 
dresdena1Author Commented:
Sorry about that. I thought I attached it.
make-gallery.php
0
 
Ray PaseurCommented:
Please use the code snippet to post code here at EE.

<?php

@ $db = mysql_pconnect("localhost","xxx","xxx") ;

if (! $db)
{
	echo ' Error: Could not connect to database.  ' ;
	exit;
}

mysql_select_db("cars",$db);

$query = 'select * from 503db where H1 = \'Custom 2008 Charger SRT\' order by index_seq,url asc';
$result = mysql_query($query);



if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}







			echo "\n<BR><a href=\"http://www.abc123.com/maketable/503/custom_2008_charger_srt.html\">Custom Audio</a>"." "  ;

		$out = fopen( "/home/abc123/public_html/maketable/503/custom_2008_charger_srt.html", "w" ) ;
  		fwrite( $out,"\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"");
  		fwrite( $out,"\n\"http://www.w3.org/TR/html4/strict.dtd\">");
  		fwrite( $out,"\n<html>");
  		fwrite( $out,"\n<head>");
  		fwrite( $out,"\n<TITLE>CUSTOM 2008 CHARGER SRT | </TITLE>");
  		fwrite( $out,"\n<META NAME=\"Keywords\" CONTENT=\" - Custom 2008 Charger SRT\">");
  		fwrite( $out,"\n<META NAME=\"Description\" CONTENT=\" - Custom 2008 Charger SRT\">");
  		fwrite( $out,"\n<link rel=\"stylesheet\" type=\"text/css\" href=\"reset.css\" />");
  		fwrite( $out,"\n<meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-1\">");
  		fwrite( $out,"\n<link rel=\"stylesheet\" type=\"text/css\" href=\"reset.css\" />");
  		fwrite( $out,"\n<link rel=\"stylesheet\" type=\"text/css\" href=\"css503m.css\" />");
  		fwrite( $out,"\n<link rel=\"stylesheet\" type=\"text/css\" href=\"ddsmoothmenu.css\" />");
  		fwrite( $out,"\n<link rel=\"stylesheet\" type=\"text/css\" href=\"ddsmoothmenu-v.css\" />");
  		fwrite( $out,"\n	<script src=\"js/jquery.js\" type=\"text/javascript\"></script>");
  		fwrite( $out,"\n	<link rel=\"stylesheet\" href=\"http://www.abc123.com/maketable/503/css/prettyPhoto.css\" type=\"text/css\" media=\"screen\" charset=\"utf-8\" />");
  		fwrite( $out,"\n	<script src=\"http://www.abc123.com/maketable/503/js/jquery.prettyPhoto.js\" type=\"text/javascript\" charset=\"utf-8\"></script>");

  		fwrite( $out,"\n<script type=\"text/javascript\" src=\"ddsmoothmenu.js\">");

  		fwrite( $out,"\n/***********************************************");
  		fwrite( $out,"\n* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)");
  		fwrite( $out,"\n* This notice MUST stay intact for legal use");
  		fwrite( $out,"\n* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code");
  		fwrite( $out,"\n***********************************************/");

  		fwrite( $out,"\n</script>");

  		fwrite( $out,"\n<script type=\"text/javascript\">");

  		fwrite( $out,"\nddsmoothmenu.init({");
  		fwrite( $out,"\n	mainmenuid: \"smoothmenu1\", //menu DIV id");
  		fwrite( $out,"\n	orientation: 'h', //Horizontal or vertical menu: Set to \"h\" or \"v\"");
  		fwrite( $out,"\n	classname: 'ddsmoothmenu', //class added to menu's outer DIV");
  		fwrite( $out,"\n	//customtheme: [\"#ffff00\", \"#fffea9\"],");
  		fwrite( $out,"\n	contentsource: \"markup\" //\"markup\" or [\"container_id\", \"path_to_menu_file\"]");
  		fwrite( $out,"\n})");


  		fwrite( $out,"\n</script>");


  		fwrite( $out,"\n</head>");


  		fwrite( $out,"\n<body>");


  		fwrite( $out,"\n<center>");
  		fwrite( $out,"\n<div id=\"container\">");

  		fwrite( $out,"\n<!--#include file=\"header.html\" -->");
  		fwrite( $out,"\n<!--closes header-->");






  		fwrite( $out,"\n<div id=\"contentbox\">");

  		fwrite( $out,"\n<H1>$H1</H1>");




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



			$id = $row["id"] ;
			$url = $row["url"] ;
			$img = $row["img"] ;
			$img_width = $row["img_width"] ;
			$img_height = $row["img_height"] ;
			$sm_img = $row["sm_img"] ;
			$sm_width = $row["sm_width"] ;
			$sm_height = $row["sm_height"] ;
			$category = $row["category"] ;
			$H1 = $row["H1"] ;


			//print a table row.

	// Pass make the request.

$i = 0 ;

  		 fwrite( $out,"\n\n" ) ;
 fwrite( $out,"<td align=center>" ) ;
// fwrite( $out,"<a href=\"$url.html\"><img src=\"http://www.abc123.com/$sm_img\" width=\"$sm_width\" height=\"$sm_height\" class=\"borderimg\"></a>" ) ;
 fwrite( $out,"<a href=\"chargerrt/$img\" rel=\"prettyPhoto[pp_gal]\" title=\"$H1\"><img src=\"chargerrt/$sm_img\" class=\"picthumb\" width=\"150\" height=\"150\" alt=\"$H1\" /></a>" ) ;

//  		 fwrite( $out,"<BR>$date" ) ;
  		 fwrite( $out,"</td>" ) ;


if($i % 3 == 1)
{
  		 fwrite( $out,"</tr><tr>" ) ;
}



  		$i++ ;



  	}
  		fwrite( $out,"\n</tr></table>");

  		fwrite( $out,"\n<!--#include file=\"footer.html\" -->");


  		fwrite( $out,"\n<script type=\"text/javascript\" charset=\"utf-8\">");
  		fwrite( $out,"\n  $(document).ready(function(){");
  		fwrite( $out,"\n    $(\"a[rel^='prettyPhoto']\").prettyPhoto();");
  		fwrite( $out,"\n  });");
  		fwrite( $out,"\n</script>");

  		fwrite( $out,"\n</BODY>");
  		fwrite( $out,"\n</HTML>");



mysql_close($db);

?>

Open in new window

0
 
Michel PlungjanIT ExpertCommented:
Also your code is unreadable.
I believe you can do this:
 $out = fopen( "/home/abc123/public_html/maketable/503/custom_2008_charger_srt.html", "w" ) ;
      fwrite( $out,'
        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN";
          "http://www.w3.org/TR/html4/strict.dtd">
        <html>
          <head>
            <TITLE>CUSTOM 2008 CHARGER SRT | </TITLE>
.
.
.
');

Open in new window


but you will need to watch

orientation: \'h\',

but that is much more readable than all the \"
0
 
Ray PaseurCommented:
Here are the essential moving parts.  Please read it over carefully because I do not have your data base, so I cannot test, but I think it's correct in principle.

$query = 'select * from 503db where H1 = \'Custom 2008 Charger SRT\' order by index_seq,url asc';
$result = mysql_query($query);
if (!$result) {
    echo "<br/>DB Error, could not query the database\n";
    echo "<br/>FAILING QUERY: $query";
    echo '<br/>MySQL Error: ' . mysql_error();
    exit;
}

// SET A COUNTER 
$n = 3;

// RETRIEVE EACH ROW FROM THE RESULTS SET
while ($row = mysql_fetch_assoc($result)) {
{
    // COPY SOME VARIABLES
    $id         = $row["id"] ;
    $url        = $row["url"] ;
    $img        = $row["img"] ;
    $img_width  = $row["img_width"] ;
    $img_height = $row["img_height"] ;
    $sm_img     = $row["sm_img"] ;
    $sm_width   = $row["sm_width"] ;
    $sm_height  = $row["sm_height"] ;
    $category   = $row["category"] ;
    $H1         = $row["H1"] ;

    // ADD SOME PADDING TO THE OUTPUT STREAM
    fwrite( $out,"\n\n" ) ;
    
    // START A ROW IF N==3
    if ($n == 3)
    {
        fwrite( $out,"<tr>" ) ;
    }
    
    // WRITE A DATA ELEMENT AND REDUCE THE COUNTER
    fwrite( $out,"<td align=center>" ) ;
    fwrite( $out,"<a href=\"chargerrt/$img\" rel=\"prettyPhoto[pp_gal]\" title=\"$H1\"><img src=\"chargerrt/$sm_img\" class=\"picthumb\" width=\"150\" height=\"150\" alt=\"$H1\" /></a>" ) ;
    fwrite( $out,"</td>" ) ;
    $n = $n - 1;
    
    // IF THE COUNTER HITS ZERO, CLOSE THE ROW AND RESET THE COUNTER
    if ($n == 0)
    {
        fwrite( $out,"</tr>" ) ;
        $n = 3;
    }
}

// AT THE END OF THE DATA, FILL OUT THE ROW
if ($n != 3)
{
    while ($n)
    {
        fwrite( $out,"<td></td>" ) ;
        $n = $n - 1;
    }
    fwrite( $out,"</tr>" ) ;
}

// CLOSE OFF THE TABLE
fwrite( $out,"</table>");

Open in new window

0
 
Ray PaseurCommented:
@Michel: I am sure this code can be "tightened up" but I wrote it out as a teaching example to illustrate the logic elements.  As I see it, these things need to happen:

1. You need to start a TR
2. You need to add 3 TD
3. You need to close a TR
4. If there are any more rows, go back to #1
5. When you're out of rows, you (might) need to pad the last row with TD
6. If you padded, you need to close a TR.

And I completely agree about making the code more readable.  One of the really good tools for that is HEREDOC notation.  You can write your HTML blocks as if they were templates, inserting your PHP variables by name, without worrying about quote marks and escape characters, and without jumping back and forth between HTML and PHP.  I'm teaching all of my students to learn HEREDOC first before they find out about the close-PHP tag!

Best to all for a good 2013, ~Ray
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
0
 
Michel PlungjanIT ExpertCommented:
I tried in vain to find the <<< which I did not know the name of so I suggested the next best thing. Thanks for giving me the name of this
0
 
Ray PaseurCommented:
I bookmarked it!
;-)
0
 
dresdena1Author Commented:
mplungjan and Ray_Paseur,
I want to say thank you very much for the help!
I was able to get mplungjan's code to work for me so I awarded the 300pts to that and 200pts to Ray_Paseur for all of the help.

With regards to how sloppy the code is, I am in no way, shape or form a programmer or coder. I am web designer and my old ISP clued me into how powerful it is to add data into a database and then write out web pages with that data.

The problem is that my old ISP closed their doors and occasionally I need to adapt what I learned from them to additional uses of php/mysql

I apologize for the overall sloppiness and confusion with all of this, I am not a student nor a programmer/coder.

I have another question open in php and any help offered is EXTREMELY appreciated.
Thank you again!
0
 
Michel PlungjanIT ExpertCommented:
YW.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.