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>
Related
<?php
$con = mysqli_connect("localhost","root","","shady");
$query = "SELECT * fROM hall1 ";
$result = mysqli_query($con,$query) or die(mysqli_error());
echo "<form action='food.php' method='post'>";
echo "<table >";
$size = 0;
while($row = mysqli_fetch_array($result))
{
$imagewidth=200;
if($size > 900)
{
echo"<tr>";
}
echo'<td width='.$td3=100 .'px > </td>' ;
echo'<td width='.$td1=200 .'px> <label><input type="radio" name="radii" value='.$row[1].' checked> <img src="'.$row['image'].'" width="200" height="200" style="margin-top:10px;"> </label></td>' ;
echo"<td width=".$td2=200 ."px> Name  : " .$row[1] ."<br> Size     : ".$row[2] ."Person <br> Price    : ".$row[3] ." SDG <br> See More </td>";
$size+= $imagewidth+$td1+$td2+$td3;
if($size > 900)
{
echo"<tr>";
}
}
echo"</table>";
echo "<BR><BR><BR><CENTER><input type='submit' name='radiii' value='next' width='200PX' height='200PX' ></a> </CENTER></b>";
echo "</form>";
}
?>
There are many problems with your code:
It's unclear what the variable size does. I'm willing to bet it's unnecessary
You are using deprecated code. The width attribute on HTML elements is no longer supported, and if you insist on using it, you should only enter the width in pixels without the px like so: <td width="200">. The <center> tag is also deprecated.
Your <label> tag is pretty much useless. What are you trying to achieve with it?
It's a bad practice to set the widths on all rows, just set the widths on the first row's cells. Even better, do not use any style directly on the HTML tags and using CSS rules instead.
Lastly, i believe it would be much more readable code to NOT echo HTML and instead use the following approach to "plug in" your variables from PHP into HTML code :
<? $a = "Some variable"; $b = 123; $c = "http://example.com/img/1.png"; ?>
<p><strong>My variable a: <?=$a?></p>
<p><strong>My variable b: <?=$b?></p>
<p><strong>My img: <img src="<?=$c?>"></p>
In short, wrap your PHP logic in <? and ?> (be sure to have short_open_tag = On in your PHP settings or you'll need to use the alternative opening tag <?php like you did.
The write plain old HTML without all the echo. Whenever you want to echo something you simply write a new PHP opening tag like so :
<? echo $a ?>
OR, the shorthand version
<?=$a?>
Now your real problem is about designing the page. And i think you are starting in the wrong order. I would suggest you
1- Build a design that works using some IDE like Adobe Dreamweaver or a freeware alternative. With that tool, make the design for 1 item (1 iteration of your while loop).
The next step is to see how you're gonna repeat it. You seem to want a Horizontal list that wraps around lines at a certain width. One way you would do that is that you would wrap all the list items with a div element for which you will set a fixed width. And inside you will have the code you have for each item repeated for all items. If your outer div has a width of 900px and each element consumes 300px in width and you have 9 items, you would have a 3x3 grid.
Here is a summary code of what i explained. In your PHP file you would have:
<div class="grid">
<? while($row = .... ){ ?>
<div class="item">
<!-- The code for the image, label and whatever information you want to have for each item -->
</div>
<? } ?>
</div>
And a CSS file which you would link in your PHP file, containing:
.grid {
width: 900px;
}
.item {
width: 300px;
}
If the information your are displaying come from user input you should sanitize it and have some sort of logic that breaks long text, either with CSS or PHP.
In short, you seem to be doing all the math in PHP so that you jump into a new line once the total width exceeds your desired grid width. This is a design issue and not a logic / programming issue. Therefore you should tackle this with CSS and not PHP.
I strongly suggest you either follow a video tutorial (there are plenty online) or read some documentations on HTML, CSS, JavaScript, PHP and MySQL in that order.
Here is a link to get you started: Mozilla Developer Network
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...
Sorry if the title is a bit vague, couldn't think of a better way to phrase it, anyway.
I'm attempting to make a page system for a website. Where you predictably start on page one, and then click page two and a different set of images appear. Each page has 12 images which are all thumbnail images. You click on the thumbnail image and lightbox brings up the high res shot.
My current problem is that I cannot link the PHP script to the images correctly. To me it looks correct but it doesn't work, so clearly not.
Info:
Thumbnails are name "thumb1.jpg" from 1-24, full images are name "img1.jpg" from 1-24
<?php
$imgs = array(12, 12, );
if(!empty($_GET["page"]))
{
$currPage = $_GET["page"];
}
else
{
$currPage = 1;
}
for($i = 1; $i<$imgs[$currPage-1]+1;$i++)
{
echo "<a href='albums/norfolk weekender 2012/img'.$imgs[$currPage][$i].'.jpg' rel='lightbox[group]'><img src='albums/norfolk weekender 2012/thumb'.$imgs[$currPage][$i].'.jpg'/></a>";
}
?>
.
Anyway, I'm unsure why it doesn't work, and any help will be much appreciated.
Ta.
John.
'.$imgs[$currPage][$i].'
It looks like you should be using " instead of ' to wrap round this embedded variable both times you reference it in the code, since your echo is distinguished by ".
Either way, looking at this it doesn't seem this array structure you've got going on is working.
"albums/norfolk weekender 2012/img".$imgs[$currPage][$i].".jpg"
Have you not considered something like this (care, it's rough); with $pageNo representing $_GET["page"]
for ( $i = ($pageNo - 1) * 12 + 1; $i <= ($pageNo * 12); $i++ )
{
echo "<a href='albums/norfolk weekender 2012/img".$i.".jpg' rel='lightbox[group]'><img src='albums/norfolk weekender 2012/thumb".$i.".jpg'/></a>";
}
If presentation (i.e. checking to see if an image exists before displaying it) is a major concern, you could use file_exists( filename ). By creating an Array like this...
$imgs = array(12, 12, );
...you are simply creating an array containing two elements of 12 (and possibly a blank element, I'm not entirely sure.) I think where you went wrong is you attempted to declare the size in the "constructor" of Array; in PHP this is not the case.
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
I have a MySQL table that contains people's names.
Using PHP, what's the best way of dividing these names up and displaying them in 3 columns.
This could be achieved using an HTML table, but would it be possible to do this using only <div>'s?
I heard that this can be done using the % operator. Would this be the best way, and how would this be done?
You could do this using the modulus operator, however it's actually possible with just CSS.
Using display: inline-block, you can get a good column effect. Take a look at this JSFiddle here. I'm only using JavaScript because I'm lazy; the <div> list would be generated by PHP in your case. If you want to confine them to a certain width, just put them in a container <div> with a fixed width.
I've come up with a solution using tables, which is really what you should be doing (you haven't given any special use cases). The code is below, as well as a working demo here.
$columns = 4; // The number of columns you want.
echo "<table>"; // Open the table
// Main printing loop. change `30` to however many pieces of data you have
for($i = 0; $i < 30; $i++)
{
// If we've reached the end of a row, close it and start another
if(!($i % $columns))
{
if($i > 0)
{
echo "</tr>"; // Close the row above this if it's not the first row
}
echo "<tr>"; // Start a new row
}
echo "<td>Cell</td>"; // Add a cell and your content
}
// Close the last row, and the table
echo "</tr>
</table>";
And to finish off, we have our column-centric layout, this time going back to divs. There's some CSS here; this should be put in a separate file, not left inline.
<?php
$rows = 10; // The number of columns you want.
$numItems = 30; // Number of rows in each column
// Open the first div. PLEASE put the CSS in a .css file; inline used for brevity
echo "<div style=\"width: 150px; display: inline-block\">";
// Main printing loop.
for($i = 0; $i < $numItems; $i++)
{
// If we've reached our last row, move over to a new div
if(!($i % $rows) && $i > 0)
{
echo "</div><div style=\"width: 150px; display: inline-block\">";
}
echo "<div>Cell $i</div>"; // Add a cell and your content
}
// Close the last div
echo "</div>";
?>