Solved

Insert <tr> at intervals

Posted on 2013-01-05
17
246 Views
Last Modified: 2013-01-06
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
0
Comment
Question by:dresdena1
  • 8
  • 5
  • 3
  • +1
17 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748192
That would be

if($i % 3 == 0)

if I am not mistaken
0
 
LVL 16

Expert Comment

by:HagayMandel
ID: 38748309
$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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748320
That would be simpler written as

if($i > 1 && $i % 3 == 0)
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38748328
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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748341
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
 

Author Comment

by:dresdena1
ID: 38748480
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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748483
Please attach the page. It was missing
0
 

Author Comment

by:dresdena1
ID: 38748494
Sorry about that. I thought I attached it.
make-gallery.php
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38748515
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
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 300 total points
ID: 38748523
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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748540
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
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38748546
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
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 38748623
@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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748645
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
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38748651
I bookmarked it!
;-)
0
 

Author Closing Comment

by:dresdena1
ID: 38748722
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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38748733
YW.
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question