Constructing HTML to output a set of numbers 5 per line - php

I am realy stuck with part of my php code! I have a range of numbers from 1 to 40 say that I pull from a table in my database and out put onto the screen using a while loop! with these numbers I am using a submit button which i will replace with a image button later on! Just now i can only get them in one line using a table but I want to get them into groups of say 5 or so colums and then go to next line print the next 5 or so colums! I have been trying for loops but they print out 1111, 2222, 3333, 4444, etc. in diffrent lines which is not what i want! I want,
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc
Please help me i have been baffeld with this for ages this is my code so far!
<?
$q3 = "SELECT * FROM tblgame";
$r3 = mysql_query($q3);
while($row2 = mysql_fetch_array($r3))
{
$game_cost = $row2['game_cost'];
echo "<p>Game ID: ".$row2['game_id'];
echo "<br>Game Day: ".$game_day;
echo "<br>Next Game Date: ".$row2['game_date_day']."/".$row2['game_date_month']."/".$row2['game_date_year'];
$fyear = $row2['game_date_year'];
$fmonth = $row2['game_date_month'];
$fday = $row2['game_date_day'];
$tmonth = $date_month;
$tyear = $date_year;
$tday = $date_day;
$days_between = abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
echo "<br>Days till next draw: ". $days_between;
echo "<br />Game Cost: £".$row2['game_cost']."</p>";
?>
<table>
<tr>
<?
$q4 = "SELECT * FROM tblnewgameitem WHERE game_id = $row2[game_id] ORDER BY 'game_number' ";
$r4 = mysql_query($q4);
$n1 = mysql_num_rows($r4);
$i=0;
while($row3 = mysql_fetch_array($r4))
{
?>
<td>
<?
if($row3['user_email'] == "")
{
?>
<form action="buyanumber.php" method="POST">
<input type="hidden" name="game_id" value="<?echo $row2['game_id'];?>">
<input type="hidden" name="num" value="<? echo $row3['game_number']; ?>">
<input type="submit" value="<?echo $row3['game_number'];?>" name="submit">
</form>
<?
}
else
{
$n = $n + 1;
echo " ".$row3['game_number']." ";
}
?>
</td>
<?
}
?>
</tr>
</table>
Please help me i have been stuck on this problem for a good number of days and its driving me loopy lol!
Thank you
Stephen

nested for-loops is the key:
$list=array();
while($row2 = mysql_fetch_array($r3)) $list[] = $row2;
$countList = count($list);
$cols = 5;
$rows = ceil($countList / $maxPerRow);
for ($i=0; $i<$rows; $i++) {
echo 'opening stuff per row... <tr> or something';
for ($j=0; $j<$rows; $j++) {
echo 'your stuff per item... might be somthing like <td>s';
}
echo 'closing stuff per row... </tr> or something';
}
something like this

I'm assuming that the 'real' problem lays somewhere between <table> and </table> and that you want to put the values returned by the fourth query (for some reason mapped to $row3) in a table with 5 columns.
Using the PHP modulo operator ('%'), you could do something like this:
<?php
$r4 = <your mysql_query>
$i = 0;
while ($row3 = mysql_fetch_array($r4)) {
if ($i % 5 == 0) { // true for 0, 5, 10, ...
echo "<tr>";
}
echo "<td>";
// what you want to put between your <td> tags comes here
echo "</td>";
if (($i+1) % 5 == 0) { // true for 4, 9, 14, ...
echo "</tr>";
}
$i++;
}
// if the number of rows is not a multiple of 5, we must clean up after ourselves:
if ($i % 5 != 0) {
echo "<td colspan=\"" + (5-($i % 5)) + "\"> </td></tr>";
}
?>
I haven't tested the code myself.
For the sake of clearity, please consider using proper indentation and consistent variable naming in your code. Also note that using a proper title and less exclamation marks in your question would improve the clearity of it.

Related

How to split a PHP loop in 2 parts?

I have a weather json from where I get a wether forecast for 8 days. My problem is that I want to show the result in a table of 2 rows of 4 days each.
I managed to do it but in a very odd way that was pure begginer's luck during a trial-error-trial attempt :-) I don't even understand quite well why it is splitting the result in 2 rows... but it works!!! The only thing I could not do was to include a "hr" line between the 2 rows, to make the table easier to read.
You can see the result here http://www.meteocaldas.com/previsao_ds.php
With current code I am displaying each day forecasted values inside the same "td" in different lines using "br". I have been reading that it is not correct to use "br" inside "td" so I am not sure that I am doing the righ thing. Wouldn't it be better to use a table with 4 columns (one for each day) and have different rows for each of the values?
Is there any way to rewrite this code to make it more efficient and look less "childish"? :-) Thanks in advance!
<?php
(...)
$decoded = json_decode($rawData, true);
?>
<table>
<?php for($k=0;$k<8;$k++){
$dailyvalue = $decoded['daily']['data'][$k];
$dailyTime = $dailyvalue['time'];
$dailyIcon = $dailyvalue['icon'];
$dailyTempMax = round($dailyvalue['temperatureMax'],0);
$dailyTempMin = round($dailyvalue['temperatureMin'],0);
(...)
?>
<!-- table for 8 day's forecast (2 rows/4 days each) -->
<td>
<?php echo strftime("%a %d",$dailyTime) ?>
<br>
<?php echo '<img src="path/'.$dailyIcon.'.png">' ?>
<br>
<?php echo $dailyTempMin.'º' ?> </span>
<br>
<?php echo $dailyTempMax.'º' ?></span>
<br>
(...)
<?php if ($k == 3) {
echo '</td></tr>';
} ?>
<?php
}
?>
</td></tr><table>
As per your comment-request, here's some sample-pseudo code, based on your code above:
<?php
(...)
$decoded = json_decode($rawData, true);
for($k=0;$k<8;$k++){
$dailyvalue = $decoded['daily']['data'][$k];
$dailyTime[$k] = $dailyvalue['time'];
$dailyIcon[$k] = $dailyvalue['icon'];
$dailyTempMax[$k] = round($dailyvalue['temperatureMax'],0);
$dailyTempMin[$k] = round($dailyvalue['temperatureMin'],0);
}
?>
<table>
<?php
echo "<tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".strftime("%a %d",$dailyTime[$k])."</td>"; // this will make the "datetime" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td><img src=path/".$dailyIcon[$k].".png></td>"; // this will make the "icon" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".$dailyTempMin[$k]."º</td>"; // this will make the "MinTemp" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".$dailyTempMax[$k]."º</td>"; // this will make the "MaxTemp" row
}
echo "</tr>";
// put stuff you want between the tables here
echo "<tr>";
for($k = 4; $k <= 7; $k++){
// proceed to do the same as above
Mind you, there are further ways you can reduce the screen clutter (like moving the table-drawing for loops into a function), but this is the general gist of it
Why don't you simply stack two different table on each other ?

<br> every 4th result from sql

Simple question of course But I still could not figure it till now :) Im pulling names out of an sql and I want to be like 1 2 3 4,then next Line like 5, 6, 7, 8 Like So
<a>Bob</a>, <a>John</a>, <a>Bob</a>, <a>John</a> <BR>
<a>Bob</a>, <a>Ion</a>, <a>Bob</a>, <a>Pon</a> <BR>
Well thats What I want it To look like But For Now Its One Row Endless with no spaces is what I acheved so far Like So :)
<?PHP
require('connect.php');
$sql="SELECT * FROM profile";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$name =$row['username'];
$power =$row['power'];
?>
<span class='user-group-<?PHP echo $power; ?>'><?PHP echo $name; ?></span> ,
<?PHP } ?>
Now What Do I need to do to have every forth result + that space :?
Use an $i counter:
require('connect.php');
$sql = "select * from profile";
$result = mysql_query($sql);
// Start at 1
$i = 1;
while($row = mysql_fetch_array($result)){
$name = $row['username'];
$power = $row['power']; ?>
<span class='user-group-<?php echo $power; ?>'><?PHP echo $name; ?></span>
<?php
// When hit 4, add <br />
if($i == 4) {
echo '<br />';
// Reset to 0. $i will then auto-increment
// to 1 when hits $i++
$i = 0;
}
else
// Add comma if not equal to 4.
echo ',';
$i++;
}

Print one table, two-column PHP associative array as three side-by-side, two-column tables

I use the following to print a 15-row, two-column table from an associative arrray in PHP:
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?
$rowCount = 0;
foreach($word_frequency as $word => $frequency) if ($rowCount++ < 15) {?>
<tr>
<td><? echo $word; ?></td>
<td<? echo $frequency; ?></td>
</tr>
<?}?>
</tbody>
</table>
It works fine but takes up too much vertical space on the page. How can I format this into three side-by-side tables of five rows and two columns each with the first group having array items 1-5, the second group 6-10, and the last group 11-15? (refer to following illustration):
key1 value1 | key6 value6 | key11 value11
key2 value2 | key7 value7 | key12 value12
...
...
key5 value5 | key10 value10 | key15 value15
I've tried various table, div, container, and multiple loop experiments with very mixed (and unsuitable) results. Thank you in advance.
Since you can also use multiple columns to achieve this visual effect, you're going to probably want to format the data ahead of time to make the code of generating the table a little cleaner.
<?php
// Format the array data so each row contains all of the columns needed
$rows = array();
$max_per_column = 5;
$max_words = 15;
$rows = array_pad($rows, $max_per_column, array());
$count = 0;
foreach ($word_frequency as $word => $frequency) {
if ($count >= $max_words) {
break;
}
array_push($rows[$count % $max_per_column], $word, $frequency);
$count++;
}
?>
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?php
foreach ($rows as $cols) {
echo '<tr><td>' . implode('</td><td>', $cols) . '</td></tr>';
}
?>
</tbody>
</table>
Try some thing like that.
<table width="100%">
<tr>
<?php
$rowCount = 0;
foreach($word_frequency as $word => $frequency) if ($rowCount < 15) { ?>
<?php if($rowCount % 5 == 0) { ?>
<td><table border=1>
<?php } ?>
<tr>
<td><?php echo $word; ?></td>
<td><?php echo $frequency; ?></td>
</tr>
<?php if($rowCount % 5 == 4) { ?>
</table></td>
<?php } ?>
<?php $rowCount++; } ?>
</tr>
</table>
The only way to do this is to use a numeric key. For example
$word_frequency[0] = array();
$word_frequency[0]['word'] = "some word";
$word_frequency[0]['frequency'] = 10;
...
$word_frequency[15] = array();
$word_frequency[15]['word'] = "some other word";
$word_frequency[15]['frequency'] = 14;
Once you have your array, you could repeat the loop as follows
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?
$rowCount = 0;
for($i = 0; $i <= 5; $i++) {
$word[0] = $word_frequency[$i]["word"];
$frequency[0] = $word_frequency[$i]["frequency"];
$word[1] = $word_frequency[$i + 5]["word"];
$frequency[1] = $word_frequency[$i + 5]["frequency"];
$word[2] = $word_frequency[$i + 10]["word"];
$frequency[2] = $word_frequency[$i + 10]["frequency"];
?>
<tr>
<?
for($x = 0; $x <= 2; $x++ ){
?>
<td><? echo $word[$x]; ?></td>
<td<? echo $frequency[$x]; ?></td>
<?
}
?>
</tr>
<?
}
?>
</tbody>
</table>
Every $i loop creates the row, while the $x loop creates the columns. This assumes, of course, that you have at least 15 items, that you're going to create only 5 rows and three columns of key/value pairs.
Well, if I were doing it, I'd probably use a ul with a css columns :D
http://davidwalsh.name/css-columns
However, that's not a very "programmerly" thing to do.
It might help that you don't have to go through the array in order.
If you look at what you have, there is a pattern to the indices:
i + 0x, i + 1x, i + 2x, ...
Where x is your number of items divided by the number of columns.
and you stop iterating when i = total / x
Sorry to be too tired to code this for you but the gist is this:
$myarray = [1 ... 15];
$columns = 3;
$arrayKeys = array_keys($myarray);
$total = count($array);
$x = floor $total / $column;
for ($i = 0; $i > $x; $i += $x + 1 ){
echo $arrayKeys[$i] . " - " . $myarray($arrayKeys[$i]);
echo $arrayKeys[$i + $x] . " - " . $myarray($arrayKeys[$i + $x]);
echo $arrayKeys[$i + ($x * 2) ] . " - " . $myarray($arrayKeys[$i + ($x * 2)]);
}
Or something like that... that's off the top of my head and I think it has some issues, but you should be able to beat that into something that works.

Find difference between two values for each row where "number" column value is same

month year customer distributor number name price
10 2012 20 8 2406163 CHEESE 50.4
10 2012 20 8 2325141 APPLE 25.2
11 2012 20 8 2406163 CHEESE 48.1
11 2012 20 8 2325141 APPLE 20.2
12 2012 20 8 2325141 APPLE 23.2
12 2012 20 8 2406163 CHEESE 46.4
I am attempting to compare two months where "number" is the same value, I'd like to find the difference between the price (if any).
Using the data above, I would want to compare months 11 & 12 (or 10 and 11, depending of these are chosen by the user). So, for months 11&12, price difference for cheese is -$1.7 and apple is -$3. This is what I am trying to do, except it should be doing this for ALL rows found in the table between two months where "number" is the same.
Here is my current code...it is currently comparing by item name rather than item number. However, for whatever reason it only finds the difference for 3 items out of 200plus items, strangely.
Thanks for any assistance.
<?PHP
$from_date = $from_month;
$to_date = $to_month;
$query = "
select * from ogi
where month BETWEEN '" . $from_date . "' AND '" . $to_date . "' GROUP BY number HAVING count(*) > 1 ;
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
//Create a variable to hold the "previous month" values
$previousname = '';
$previousprice = '';
//Check each record from your query
foreach($rows as $row) {
//If not first time around && same item name as previous
if($previousname != '' && $previousname == $row['name']) {
//subtraction calculation here
if ($row['price'] <= $previousprice) {
$difference = "(Price Lowered) Price difference of $";
$result = $previousprice - $row['price'];
$percent = round(100.0*($previousprice/$row['price']-1));
?>
<tr>
<td><?php echo "" . $row['name'] . ""?></td>
<td><?php echo $difference; ?><?php echo $result ?> </td>
<td><?php echo $percent; ?> %</td>
</tr>
<?
} elseif ($row['price'] > $previousprice) {
$result = $row['price'] - $previousprice;
$percent = round(100.0*($previousprice/$row['price']-1));
$addition = "(Price Higher) Price difference of $";
?>
<tr>
<td><?php echo "" . $row['name'] . ""?></td>
<td><?php echo $addition; ?><?php echo $result ?> </td>
<td><?php echo $percent; ?>%</td>
</tr>
<?
}
}
else {
?>
<!-- <tr>
<td><?php echo "" . $row['name'] . ""?></td>
<td></td>
<td></td>
</tr> -->
<?
}
//Assign the "previous month" value
$previousname = $row['name'];
$previousprice = $row['price'];
}
?>
<?
}
else {
?>
<form action="" method="post">
Choose Months to Compare:<br>
Customer: <input type="text" name="customer"><br>
Month 1: <input type="text" name="from_month"><br>
Month 2: <input type="text" name="to_month"><br>
<input type="submit" value="Compare">
</form>
<?
}
?>
What about something like:
SELECT a.number, a.name, (a.price - b.price) as pdiff
FROM table a, table b
WHERE a.number = b.number
AND a.month = montha
AND b.month = monthb;
If I didn't make any mistake this query should give you the needed info:
(where montha = 10 and monthb = 11 for example)
Hope this helps.

Change for in PHP with table

<table><tr>
<?php
for($i=0;$i<15;$i++) {
if($i%5 == 0) {echo '</tr> <tr>';}
?><td><?php echo $i ?></td>
<?php
}?>
</tr>
</table>
this generate:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
how can I make:
0 3 6 9 12
1 4 7 10 13
2 5 8 11 14
?
You need a nested loop
<table>
<?php
$rows = 3;
for($i=0 ; $i < $rows ; $i++ ) {
echo "<tr>";
for( $j = 0 ; $j < 5 ; $j++ ) {
echo "<td>" . ($j * $rows + $i) . "</td>";
}
echo "</tr>";
}
?>
</table>
I tried to make the variable names descriptive:
<table>
<?php
// Set the number of rows, cols, and starting number here:
$number_rows = 3;
$number_cols = 5;
$starting_num = 0;
// You can use foreach w arrays... much easier
$rows = range(0,$number_rows - 1);
$cols = range(0,$number_cols - 1);
foreach($rows as $one_row) {
?>
<tr>
<?php
foreach($cols as $one_col) {
// Do the calculation
echo "<td>" .
($starting_num + $one_col + ( max($rows) * $one_col ) + $one_row) .
"</td>";
}
?>
</tr>
<?php
}
?>
</table>
Working example like in the OP.
Now let's say you want to go from (1300-1431), then you start at 1300 and want a 4 x 8.
$number_rows = 8;
$number_cols = 4;
$starting_num = 1300;
Like this.
There are two "tricks."
The first is using range() to quickly define an array integers. I find arrays more pleasant to work with than raw numbers, since arrays can be worked on with the intuitive construct of foreach().
The second is figuring out how to know what number to print if you have the column, row, and starting, number. It's simplest to figure out the numbers for the first row and go from there. Let's number the rows and cols from 0. So col:0 row:0 will be the starting number. Col:1 Row:0, the number to the right, will just be the starting number + one (the column number) + the number of rows less one (easiest to see by looking at the matrix of number), and the number of rows less one is the maximum number in the rows array. So for the first row we have:
$starting_num + $one_col + ( max($rows) * $one_col )
then all we just add the row number to take that into account, and we've got it all:
$starting_num + $one_col + ( max($rows) * $one_col ) + $one_row
Tested example with given start and end:
<table>
<?php
$start = 1300;
$end = 1432;
$n = $end - $start + 1;
$cols = 5;
$rows = ceil($n / $cols);
for($i=0 ; $i < $rows ; $i++ ) {
echo "<tr>";
for( $j = 0 ; $j < $cols ; $j++ ) {
$val = $j * $rows + $i;
echo "<td>";
echo ($val < $n) ? $val + $start : ' ';
echo "</td>";
}
echo "</tr>";
}
?>
</table>

Categories