I have a SQL pupil's list sorted by classes and this list goes into TCPDF to create a PDF 2 columned list. My issue is that I can't find the way to break the line.
What I know is that a column can have max 59 rows. So, if the next group would not fit they should go to the next column.
The theory would be to check the actual line
$html=$html.'<tr><td width="40"> </td><td width="90"> </td><td width="50"> </td><td width="45"> </td><td width="45"> </td></tr>'; //35
while($classok = mysql_fetch_array($classquery))
{
$classes=$classok['id'];
$classnum=mysql_num_rows(mysql_query("SELECT class_id FROM pupils WHERE class_id=".$classes." AND pupils.torolve=0 and pupils.statusz=1"));
I would like here something that would shift the rows down if the next class would reach more than 59 lines. Like:
$html=$html.'<tr><td></td></tr>';
but I can't put the condition in the right way...
The problem is that the previous group randomly finishes so the next class should start the on the new page.
$headek=$headek.'<b><tr><th>D.O.B.</th><th colspan="2">';
$headek=$headek.$classok['name'].'</th><th colspan="2">';
$headek=$headek.$classok['initname'];
$sum=$sum+$classnum;
$headek=$headek.'('.$classnum.')'.'</th></tr></b>';
$html=$html.strtoupper($headek);
$pupilssql="SELECT pupils.extra_functions, pupils.name, pupils.dateofbirth, pupils.sex, YEAR(pupils.dateofbirth) AS year, MONTH(pupils.dateofbirth) AS month, DAY(pupils.dateofbirth) AS days, pupils.name, pupils.firstname, pupils.class_id FROM pupils, classes WHERE pupils.class_id=classes.id AND pupils.torolve=0 and pupils.statusz=1 AND class_id=".$classes." ORDER BY pupils.name ASC";
$pupilsquery=mysql_query($pupilssql);
while($result = mysql_fetch_array($pupilsquery))
{
etc...
Everything is working well except this column break that I can't put in code... Anyone's help would be appreciated.
They will need to be separate tables. Start a new table for each block of 59 pupils and then use CSS to float the tables so they will stack up next to each other. Or you can be lazy and put those tables inside a table and do EZ formatting (yuck).
Add a variable before your loop: $i = 0;
Iterate it at the beggining of your loop: $i++;
At the end of your loop, use if and modulus to print whatever seperator you want every 59 (or however many) lines: if($i % 59 == 0) echo '<br />';
change <br /> to whatever code you need to seperate the sections
Related
Each table is to be produced by one loop; a for loop and a while loop creating two separate tables.
Alternate rows shall be coloured using html attribute names
Every cell containing the result of the square of a number (1x1, 2x2, 3x3 etc) shall also have distinctive background using a html attribute name
Create the times table from 1 to12. (ie: 1x1 ... 12x12) - for both times tables.
Please display only the result (i.e: 1, 2, 4, 144) for the FOR loop table and display the calculation and result (i.e: 1x1=1, 2x2=4, etc) for the WHILE loop table.
<head>
<meta charset="utf-8">
<title>Multiplication Table</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Multiplication Table with a "forloop"</h1>
<table border ="1" align="center" width="80%">
<?php
// Create first row of table headers
$l = 12;
$c = 12;
echo '<th>X</th>';
for ($l = 1; $l <12; $l++){
echo "<th bgcolor=#d3d3d3>". $l . "</th>";
}
//set alternating table row colors
for($i = 1; $i <=$l ; $i++){
if($i%2 == 0){
echo "<tr bgcolor =#CAE3FF>";
echo "<th bgcolor =#d3d3d3>$i</th>";
}else{
echo "<tr bgcolor =#d3d3d3>";
echo "<th bgcolor =#d3d3d3>$i</th>";
}
//Set color for squared numbers
for($c = 1; $c<13; $c++){
if($i == $c){
echo "<td bgcolor = #ffffff>".$i * $c . "</td>";
}else{
echo "<td>".$i * $c ."</td>";
}
}
echo "</tr>";
}
?>
</table>
<br><br>
<h1 align="center">Multiplication Table with a "Whileloop"</h1>
<table border ="1" align="center" width="80%">
<?php
$r = 12;
$c = 12;
echo "<th>X</th>";
$r = 1;
while ( $r<= 12) {
echo "<th bgcolor = #d3d3d3>".$r. "</th>";
$r ++;
}# End of While loop
echo "</tr>";
$x = 1;
while ( $x <= $r) {
if($x % 2 == 0){
echo "<tr bgcolor =#CAE3FF>";
echo "<th bgcolor =#d3d3d3>$x</th>";
}else{
echo "<tr bgcolor =#d3d3d3>";
echo "<th bgcolor =#d3d3d3>$x</th>";
} # End of if-else 1
$y = 1;
while ( $y <=12) {
if($x == $y){
echo "<td bgcolor = #ffffff>".$x. "x" .$y."=".$x * $y . "</td>";
}else{
echo "<td>".$x. "x" .$y."=".$x * $y ."</td>";
} // End of if-else 2
$y ++;
}
$x++;
} # End of the main While loop
?>
</tr>
</table>
</body>
</html>
Since you're new, I'll do for you what I wish someone had done for me.
I've re-written your code to highlight some elements of simplification. If you'll bear with me, this will hopefully save you mountains of time and frustration. :-)
Like most beginners, you are using nested if statements because you have not yet learned to think like a professional programmer. You're mentally looping through the cells in your head and you're making decisions about them. Your code reflects that.
Lets look at what you did:
You needed to fill up this block, so we randomly put an X here. That's somewhat OK, but there's a better way.
You create a header row. also, not bad.
You're making a decision on each cell based on its content. But this is where you start to make things complicated. Not only are you needlessly printing the tr bgcolor (doesn't matter when you change the cell color), but you'r making an either or decision with an else inside a loop. That's hard to read, hard to maintain, and if you continue to develop this way, other developers will want to strangle you.
You have a secondary for loop to handle squares. This is wholly unnecessary.
But it's OK! You should see the trash I wrote when I was starting out!
Let's change the way you think to fix the code.
You probably did not start out by drawing your table on a piece of paper and coloring in your cells, but you should have. It helps you visuallize what you're about to do. I had the benefit of just running your code to see what you were doing. Quite honestly - I wasn't able to visualize it just looking at your code.
After I ran it, I saw you have three objectives:
Show odds in grey (also the default color)
Show evens in blue
Show squares in white
Now, let's think about what actually has to go on here to make this happen.
We need a header
We need to loop through 1 to 12 twice to create the table.
We need a header column so we can create that nice "x * y" lookup table
We need to change the cell color based on its value.
So, let's use a couple of rules to force us to write cleaner, better code.
Implement separation of concerns so that any given section of code is only doing one thing.
Avoid nested loops and nested if's like the plague. Only use them when necessary. (We need a nested loop to do our mutiplication, so it's ok there).
'else' is never necessary.
When making decisions, allow the decision to cascade down a decition tree until a matching condition is found.
KISS
Don't repeat yourself.
Here's the resulting code (note" I am using images because it will be easier for me to annotate the changes. The code is here in this gist for you.
The HTML
The HTML section is at the bottom of the code, and contains two simple PHP snippets to print the header and print the table.
Printing the header
Keeping with simplicity and separation of concerns, this does one thing: it prints the header. I also changed $l to $i since i is more synonymous with an index or pointer in programming.
And, I fixed a bug. You were using <12 instead of <=12 so your last column wasn't printing.
Printing the table
Again, separating out concerns, this function only wants to print the table. It doesn't care about the cells.
Here's what we're doing:
$x represents the row number.
Here, I open the row. Because each time $x increments, I should be starting a new row.
$y represents the column. I need this here only because the column matters to the row. I am NOT concerned with printing the cell in this function.
This function separates teh concern of dealing with the cell to another function aptly named print_cell.
After I have printed all the cells for the row, I should close it out so I can start a new row, or finish out the table.
Printing the cells
Again - separation of concerns: I only want to deal with printing the cell. And, thus far, I don't care about colors!
I need $x and $y, so I receive them here.
I am using printf and a format string instead of concatenation. Anytime I see an abundance of concatenation, I know I am dealing with a novice programmer who doesn't know any better. You now know better. :-)
This line determines the color, but you can see I refactored out the color logic into its own function because this function doesn't care about making color decisions - only about printing the cell.
This line is a convenience so I can deal with $n instead of $x * $y. It fills up the symbol table uselessly, but sometimes you can just splurge on a little extra memory.
This is a ternary operation, which is a basic shorthand for if...else. It doesn't violate the "else is never necessary" rule because it is limited to a single line and an "either or" condition, whereas "else" is a catch-all. It also avoids block if decisions. It's still clean code.
Here, I am printing the cell using printf.
Choosing cell colors
First, there is no need to color the <tr> because we are choosing all the cell colors, which would just override it anyway. So we don't care about <tr>'s bgcolor.
Next, Please note that the numbers in the image below do not go from top to bottom like the others 1 is at the bottom for a reason!
This function is dedicated to choosing a cell color based on its content. We want it to execute from top to bottom, and return the color for the cell as soon as it gets a match. Therefore, we put the "special" colors towards the top of the function and default, non-special ones at the bottom.
This is the default value. Cells are grey unless they are special. In order for a cell to be grey, they cannot match any of the rules above it.
Our first column for each row is actually a header. In your original code, you were creating extra code to handle this, but in reality, it's just column 0. When $y == 0, make it blue.
This is our first "special" condition for a cell color. If it's a square it's white (doesn't matter if it is even or odd).
This is our next special condition, but not as special as squares. If it's even, it's blue.
What's very important about this type of structure is that it allows the processor to return a value from a function the instant it gets a result. Nested if's, on the other hand, have to exit if after if after if after if after else before they can exit the function. This doesn't matter in an application like what you've written, but at scale when every CPU cycle counts, that's important. Plus, this is DRASTICALLY easier to read than what you wrote with all the nested statements and concatenated strings.
Conclusion
Welcome to the programming club. I hope you found this useful and helpful. Keeping your code clean and following these pracitces (as well as knowing the PSRs, and how to refactor) will go a long way in making you an excellent addition to our community. (Not just SO, but the programming community in general).
Knowing design patterns is extremely helpful too.
Remember: "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." Because sometimes that violent psychopath will be you in 6 months when you're trying to figure out what the hell you did when you wrote "that code" six months ago.
Here's the re-written code
<?php
/**
* Prints the top row of the table.
* */
function print_header() {
echo '<th>X</th>';
$format = "<th bgcolor=#d3d3d3>%s</th>";
for( $i = 1; $i <=12; $i++) {
printf($format,$i);
}
}
/**
* Determines the color of the cell.
* */
function get_color($x, $y) {
//These are header rows / columns.
if($y == 0) return "#CAE3FF";
//If they are squared, x == y. This is the override.
if( $x == $y ) return "#ffffff";
//If they are even, return blue.
if( ($x * $y ) % 2 == 0 ) return "#CAE3FF";
//what's left over is either odd or weird. Return grey.
return "#d3d3d3";
}
/**
* Prints the cell
* */
function print_cell($x, $y) {
$format = "<td bgcolor = %s>%s</td>";
$color = get_color($x,$y);
$n = $x * $y;
$output = ( $n == 0 ? $x : $n);
printf($format,$color,$output);
}
/**
* Prints the rows of the table and holds the primary loop
* */
function print_table() {
for($x = 1; $x <=12; $x++) {
echo "<tr>";
for($y = 0; $y <=12; $y++) {
print_cell($x,$y);
}
echo "</tr>";
}
}
?>
<head>
<meta charset="utf-8">
<title>Multiplication Table</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Multiplication Table with a "forloop"</h1>
<table border ="1" align="center" width="80%">
<?php print_header() ?>
<?php print_table() ?>
</table>
</body>
</html>
my smarty code is like this i want to add new tr after adding two td $k is counter variable with this code i can not add new tr after every two td
{section name="sec" loop=$dataArray}
<tr>
{if ($k%2) == 0}
<td>{$dataArray[sec].itemNm}</td>
<td>{$dataArray[sec].rate}</td>
<td>{$dataArray[sec].unitId}</td>
<td>{$dataArray[sec].packing}</td>
</tr>
{/if}
{/section}
My Php Select Query is like
$selectdata = "SELECT *,itemNm FROM price
JOIN item ON item.itemId = price.itemId
WHERE price.companyId = ".$companyId;
$selectdataRes = mysql_query($selectdata);
while($dataRow = mysql_fetch_array($selectdataRes))
{
$dataArray[$k]['priceId'] = $dataRow['priceId'];
$dataArray[$k]['itemNm'] = $dataRow['itemNm'];
$dataArray[$k]['rate'] = $dataRow['rate'];
$dataArray[$k]['unitId'] = $dataRow['unitId'];
$dataArray[$k]['packing'] = $dataRow['packing'];
$k++;
}
You increment $k every loop of mysql_fetch_array, which means $k is the number of the row (aka TR in your HTML). If your SQL query returns 4 lines, each containing a priceId, itemNm, rate, unitId and packing.
Normally in your HTML, to represent it in a common table, you would have 4 lines TR (one TR for each row) with a column TD for each data you want to display (one TD for each data).
{section name="sec" loop=$dataArray}
<tr>
<td>{$dataArray[sec].itemNm}</td>
<td>{$dataArray[sec].rate}</td>
<td>{$dataArray[sec].unitId}</td>
<td>{$dataArray[sec].packing}</td>
</tr>
{/section}
If you perform a $k%2 == 0, you reach it every two rows (every two TR), not every two TD. If you want to close TR and open new TR every two TD and not every two TR, you have to handle your TDs in a loop and start another incrementing variable like this (example neither with smarty nor in any language in particular, just an idea of algorithm) :
for($k=0;$k<$numLines;$k++)
{
<tr>
for($l=0;$l<$numColumns;$l++)
{
if($l > 0 && $l%2 == 0)
{
</tr><tr>
}
<td>$myData[$l]</td>
}
</tr>
}
Hoping it helps :)
Your question is very hard to understand...
Do you want to split every data row in two table rows?
Since you have a static template, you can add table rows inside your loop, whereever you want. I see no need to use multiple loops.
{section name="sec" loop=$dataArray}
<tr>
<td>{$dataArray[sec].itemNm}</td>
<td>{$dataArray[sec].rate}</td>
</tr>
<tr>
<td>{$dataArray[sec].unitId}</td>
<td>{$dataArray[sec].packing}</td>
</tr>
{/section}
if this does not fit your needs, maybe could you provide an example output as you need it?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Hello. I have an assignment 9.2 to do and have no idea where to start.
I have made the index.php which allows the user to input the width and height of the table.
Here is the code for that:
<html>
<head>
<title>Assignment 9.2</title>
</head>
<body bgcolor="black" text="white">
<form method="post" action="table.php"
<strong>Please select an integer for the width:</strong>
<input type="text" name="width" size="10">
<br>
<strong>Please select an integer for the height:
<input type="text" name="width" size="10">
<input type="submit" value="Submit">
</form>
</body>
</html>
I do not know where to start on making the table. I do not expect to have this
done for me.. but to simply explain where to start and the php codes I need to use.
Again.. this is for 9.2 which is shown in the picture attached.
Okay, so this is a fairly simple thing to do if you understand how html tables are laid out in code...
HTML table format
The first step is to understand how tables are laid out in html...
3x2 table
For a 3 columned / 2 rowed table the code would look something like this...
Pseudo
opening table tag
opening row tag
cell tag
cell tag
cell tag
closing row tag
opening row tag
cell tag
cell tag
cell tag
closing row tag
closing table tag
HTML
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
I don't know how much you know about html but hopefully that should make sense if not there are a wide variety of resources available that can explain the tags used etc...
PHP Code
At this point we're going to skip the input of width and height (as you already have the code for that) and assume that you've captured them as follows:
$in_width = $_POST['width'];
$in_height = $_POST['height'];
So now we know what the width and height of the table is going to be we can look at how to put them together:
If you look back at the example table code above you'll see that tables are rendered one row at a time in the format:
First row first column
First row second column
First row third column
Second row first column
...and so on...
This might be more clear by looking at the numbers in your screen grab above.
Given that we know how a html table is structured we can determine that we can use two loops* (the second one embedded in the first) to produce the desired output.
(The rows will be the outer loop and the columns will be in the inner loop - see example html code above)
Pseudo code
start table
for each row {
start row
for each column {
print cell
}
end row
}
end table
*You can use any loop you're comfortable with (i.e. for or loop) they do the same thing
If you want to do this yourself, I suggest that you stop reading here. Spoiler follows...
Spoiler
Two while loops
$in_height = $_POST['height']; // Get table height
$in_width = $_POST['width']; // Get table width
$counter = 1; // Start the counter at 1
$temp_width = 0; // Set temporary variable for width(second loop)
echo "<table>"; // Print opening tag for table
while($in_height > 0){
echo "<tr>"; // Print opening tag for row
$temp_width = $in_width; // Set temp_width to width of table
while($temp_width > 0){
echo "<td>$counter</td>"; // Print cell with counter value
++$counter; // Increment counter
--$temp_width; // Decrement temp_width
}
echo "</tr>"; // Print closing tag for row
--$in_height; // Decrement height
}
echo "</table>"; // Print closing tag for table
Two for loops
Just for demonstration purposes...
$in_height = $_POST['height'];
$in_width = $_POST['width'];
$counter = 1;
$temp_width = 0;
$temp_height = 0;
echo "<table>";
for($temp_height = 0; $temp_height < $in_height; $temp_height++) {
echo "<tr>";
for($temp_width = 0; $temp_width < $in_width; $temp_width++){
echo "<td>$counter</td>";
++$counter;
}
echo "</tr>";
}
echo "</table>";
You could also mix and match loops...
I have the following table in mysql:-
id | bandname
1 | a perfect circle
2 | aerosmith
3 | b.b king
4 | cat stevens
I am fetching all of the results in a single query with:-
$result = mysql_query("SELECT id, bandname FROM bands ORDER BY bandname ASC");
On my page I have A-Z anchor links which bring up a new tab:-
<ul class="tabs-nav">
<li class="active">0-9</li>
<?php
// Print a-z link
for ($i=97; $i<=122; $i++) {
$curletter = chr($i);
echo '<li>'.$curletter.'</li>';
}
?>
</ul>
I'm having trouble getting the bands listed under their tab. Currently my code is:-
<div class="tabs-container">
<?php
// Print a-z tabs
for ($i=97; $i<=122; $i++) {
$curletter = chr($i);
?>
<div class="tab-content" id="<?php echo $curletter; ?>">
<?php
while($bands = mysql_fetch_array( $result )) {
$bandname = $bands['bandname'];
$bandid = $bands['id'];
$bandletter = strtolower(substr($bandname , 0 , 1));
}
if($curletter==$bandletter) {
echo '<a href="'.$bandid.'/" title="'.$bandname.'>'.$bandname.'</a>';
}
?>
</div>
<?php } ?>
</div>
I know this is incorrect because I'm calling the while loop inside the for loop and that just doesn't seem right to me - as every iteration of the A-Z tab creation process will have to run through the while loop.
If I will be dealing with say 5,000 bands what is the best approach for this? One sql result looped multiple times, one result with each band then held in an alphabetical array, or an ajax sql query whenever a user clicks on one of the anchor links?
None of this even starts to deal with the 0-9 tab which I think will be an issue itself given my current code. Any pointers really would be appreciated.
I have searched for an answer but not found something similiar to my question :)
Though I wouldn't recommend the method you've used at all, if you want to keep it as simple as you have then you need to extract all of the band names using the while before you enter the name looping foreach by putting them into a temporary array, or better still before any output takes place. This will allow you to use foreach() on this array instead of the while. You could also sort these into arrays by letter too, making it simpler to see which letters have bands that start with it
Some extra tips:
Use range() instead of the for($i = ... ) and chr() for the letters listings
Give your href values more than just the letter as the id (aesthetic but certainly better) such as letter-a letter-b and so on
If you're using 5000+ records you should be serving these on separate pages in my opinion with pagination rather than on one large page of bands
If these are not going to change very often, you'd be best using a caching system of some sort to keep database querying to a minimum
If you use the array by letter method I've given above, you can use the count() function to add the band number counts to the letter listings (and even hiding letters you have no bands for)
Lets start with;
echo $query_row['winkels'];
This will echo;
<td style="margin-left:3px;"><img src="logo/15.png"/></td> <td style="margin-left:3px;"><img src="logo/11.png"/></td>
Out of my MySql Database, but on the page it will echo one image. If I put more in like example;
<td style="margin-left:3px;"><img src="logo/15.png"/></td> <td style="margin-left:3px;"><img src="logo/11.png"/></td> <td style="margin-left:3px;"><img src="logo/15.png"/></td> <td style="margin-left:3px;"><img src="logo/11.png"/></td>
It will echo 2 images.
When I have more than 20 images shown I want to reduce it to 5 images.
How can I do that?
For example;
$winkels_inject = $query_row['winkels'];
$sub_winkels = substr($winkels_inject, 0, 191);
echo $sub_winkels;
This is perfect when trying to reduce text, but that is what it does when I use it. It reduces the image links and removes html so the images will not be shown. So no image will be shown at all.
How to fix this?
Regards,
F4LLCON
It seems you have a design problem, the only thing you would need to store in a DB, is the number and then every number in a different row.
Anyway, a quick and very dirty solution:
$string_with_breaks = str_replace('td> <td', 'td>__break_here__<td', $query_row['winkels']);
$img_array = explode('__break_here__', $string_with_breaks);
// loop through array and only echo the first 5 elements
$count = 0;
foreach($img_array as $store)
{
echo $store;
$count++;
if ($count > 4)
{
break;
}
}
Miss (or add...) a space between the td tags and it will not work anymore...