php foreachloop with html tables - php

I have a foreach loop for 'n' number of cubicles.
I want to display 4 cubicles in each row and reaminig in next row.
How to limit 4 cubicles in each row within foreach loop.
Right now below code display all cubicles in one row
print '<table border="2">';
print '<tr>';
foreach($Cubicle as $cubicle )
{
print '<td>';
if($nodeStatus == '0'){
printf('%s ', $nodeId,$insert);
}
elseif($nodeStatus == '1'){
printf('%s ', $nodeId,$insert);
}
else{
printf('%s ', $nodeId,$insert);
}
print '</td>';
}

Use array_chunk PHP Manual to obtain the 4 values per each row:
echo '<table border="2">';
foreach(array_chunk($Cubicle, 4) as $row )
{
echo '<tr>';
foreach($row as $col)
{
echo '<td>', $col /* your column formatting */, '</td>';
}
echo '</tr>';
}
echo '</table>';

print '<table border="2">';
print '<tr>';
foreach($Cubicle as $num => $cubicle )
{
if ($num%4 == 0)
{
print '</tr><tr>';
}
print '<td>';
...

This should do the trick, and is flexible:
function printTable($cubicles, $items_per_row) {
print '<table border="2">';
while($row = array_splice($cubicles, 0, $items_per_row)) {
print '<tr>';
printRow($row, $items_per_row);
print '</tr>';
}
print '</table>';
}
function printRow($cubicles, $items_per_row) {
for($i=0; $i<$items_per_row; $i++) {
print '<td>';
print (isset($cubicles[$i]) ? $cubicles[$i] : ' ');
print '</td>';
}
}
printTable($Cubicle, 4);

print '<table border="2">';
print '<tr>';
$rowNum = 0;
foreach($Cubicle as $cubicle){
$rowNum++;
if($rowNum % 4 == 0){ echo '<tr>'; }
print '<td>';
if($nodeStatus == '0'){
printf('%s ', $nodeId,$insert);
}
elseif($nodeStatus == '1'){
printf('%s ', $nodeId,$insert);
}
else{
printf('%s ', $nodeId,$insert);
}
print '</td>';
if($rowNum % 4 == 0){ echo '</tr>'; }
}

try this.
print '<table border="2">';
$s=0;
foreach($Cubicle as $cubicle )
{
if($s == 0){
echo $open_tr = '<tr>';
}else if($s % ceil(count($Cubicle)/4) == 0){
echo $open_ul = '</tr><tr>';
}else{
echo $open_ul = '';
}
print '<td>';
if($nodeStatus == '0'){
printf('%s ', $nodeId,$insert);
}
elseif($nodeStatus == '1'){
printf('%s ', $nodeId,$insert);
}
else{
printf('%s ', $nodeId,$insert);
}
print '</td>';
if($s == (count($Cubicle) - 1)){
echo '</tr>';
$s++;
}
}

print '<table border="2">';
print '<tr>';
$cellIndex = 0;
foreach($Cubicle as $cubicle )
{
if ((++$cellIndex % 4) == 0) {
print '</tr><tr>';
}
print '<td>';
...

The basic technique consist on using a numeric counter to keep track of the column and the modulus operator to keep it in within the column range. Also, since it's an HTML table you may also want to fill missing cells so the display looks good.
Here's an example:
<?php
define('NUM_COLUMNS', 4);
$cubicle = array('A', 'B', 'C', 'D', 'E', 'F');
if( empty($cubicle) ){
echo '<p>No cubicles found.</p>';
}else{
echo '<table>' . PHP_EOL;
$column = 0;
foreach($cubicle as $cubicle_name){
if( $column==0 ){
echo '<tr>';
}
echo '<td>' . htmlspecialchars($cubicle_name) . '</td>';
if( $column==NUM_COLUMNS-1 ){
echo '</tr>' . PHP_EOL;
}
$column = ($column+1) % NUM_COLUMNS;
}
// Fill gaps
if( $column>0 ){
while( $column<NUM_COLUMNS ){
echo '<td>—</td>';
$column++;
}
echo '</tr>' . PHP_EOL;
}
echo '</table>' . PHP_EOL;
}

Related

PHP: Show data from mysql database in table

I am new to php and trying to fetch data from database and trying to show it in html table. My issue is total number of returned record is 13 but in table it is just showing 12 record( it is skipping first record in html table) my code snippt is as below
$num_rows = mysql_num_rows($result);
echo $num_rows;
if ($num_rows > 0) {
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table.= '<th>Mil Purchy</th><th>Next Mil Purchy</th><th>total Missing</th><th>Missing From-To</th>';
for ($x = 0; $x <= $num_rows; $x++) {
while ($row = mysql_fetch_array($result)) {
if ($i % 1 == 0) {
// if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table.= '<tr><td>' . $row[0] . '</td>';
$dyn_table.= '<td>' . $row[1] . '</td>';
$dyn_table.= '<td>' . $row[2] . '</td>';
$dyn_table.= '<td>' . $row[3] . '</td>';
} else {
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table.= '</tr></table>';
}
echo $dyn_table;
}
and on submit button I have written following code
<fieldset>
<?php
if ($_GET) {
if (ISSET($_GET['submit'])) {
// echo "<script> alert('waiting for function') </script>";
$From_Date = $_GET['DateFrom'];
$To_Date = $_GET['DateTo'];
Sequece($From_Date, $To_Date);
}
}
?>
</fieldset>
before anything it is important that you use mysqli() functions instead of mysql() because mysql() function series are being departed from php. Also you missed some <tr> and </tr>s. so here is your fixed code:
<?php $num_rows = mysqli_num_rows($result);
echo $num_rows;
if($num_rows > 0){
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table .= '<tr><th>Mil Purchy</th><th>Next Mil Purchy</th><th>total Missing</th><th>Missing From-To</th>';
while($row = mysqli_fetch_array($result))
{
if ($i % 1 == 0) { // if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table .= '</tr><tr><td>' .$row[0] . '</td>';
$dyn_table .= '<td>' .$row[1]. '</td>';
$dyn_table .= '<td>' .$row[2]. '</td>';
$dyn_table .= '<td>' .$row[3]. '</td>';
} else {
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table .= '</tr></table>';
echo $dyn_table;
}?>
Also you are creating many <script> inside the <table> structure code, it is not wrong and it works but it is bad HTML so I recommend that you store all <script>s in an array and after creation of table, print out the array. any by the way, why sending many alerts? why not only print the alerts only?
Database is returning correct records that is 12.
You made a mistake in the following line of code:-
for ( $x = 0; $x<= $num_rows; $x++){
Simply replace above code block with the following one:-
for ( $x = 0; $x < $num_rows; $x++){
Here you are trying to get ($num_rows + 1) = 13 records from the database that's why you are not getting data for last record that is 13.
You do not need a for loop. Your while loop will stop when there are no more records. That's why it's there.
Remove for loop and check it may be work.
$num_rows = mysql_num_rows($result);
echo $num_rows;
if ($num_rows > 0)
{
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table.= '<th>Mil Purchy</th><th>Next Mil Purchy</th><th>total Missing</th><th>Missing From-To</th>';
while ($row = mysql_fetch_array($result)) {
if ($i % 1 == 0)
{
// if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table.= '<tr><td>' . $row[0] . '</td>';
$dyn_table.= '<td>' . $row[1] . '</td>';
$dyn_table.= '<td>' . $row[2] . '</td>';
$dyn_table.= '<td>' . $row[3] . '</td>';
}
else
{
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table.= '</tr></table>';
echo $dyn_table;
}
13 will not divisible by 3 so it only shows 12 results
<?php
$num_rows = mysql_num_rows($result);
echo $num_rows;
if ($num_rows > 0) {
$i = 0;
$dyn_table = '<table class="gridData">';
$dyn_table .= '<th>Mil Purchy</th>
<th>Next Mil Purchy</th>
<th>total Missing</th>
<th>Missing From-To</th>';
while ($row = mysql_fetch_array($result)) {
if ($i % 1 == 0) { // if $i is divisible by our target number (in this case "3")
echo "<script> alert('$i') </script>";
$dyn_table .= '<tr><td>' . $row[0] . '</td>';
$dyn_table .= '<td>' . $row[1] . '</td>';
$dyn_table .= '<td>' . $row[2] . '</td>';
$dyn_table .= '<td>' . $row[3] . '</td>';
} else {
echo "<script> alert ('in else statement') </script>";
}
$i++;
}
$dyn_table .= '</tr></table>';
echo $dyn_table;
}?>

format when column has specific name,

the roblem is where there is the punch commentator
i need when the column has INTER name or OUTER name to format the content of the $cell
with $cell=number_format($cell,2,',','.')
i'm just starting using php so don be too specific thanks
<?php
// printing table rows
$rigapadi = 1 ;
while($row = mysql_fetch_row($result))
{
echo "<tr>";
$rigapadi=$rigapadi+1;
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
if ($rigapadi % 2 == 0) {
# if column name = 'INTER' or 'OUTER' $cell = number_format($cell, 2, ',', '.');
echo "<td align=\"center\">$cell</td>";
} else {
echo "<td bgcolor=\"#E9EEF5\" align=\"center\">$cell</td>";
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
echo "<p/>";
?>
The mysql_ are obsoltes. You must not use them. And please indent your code properly when you ask for help.
<?php
$rigapadi = 1;
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
$rigapadi++;
foreach($row as $name => $cell) {
if($rigapadi % 2 === 0) {
if($name === 'INTER' || $name === 'OUTER') {
echo '<td align="center">' . number_format($cell, 2, ',', '.') . '</td>';
} else {
echo '<td align="center">' . $cell . '</td>';
}
} else {
echo '<td align="center" bgcolor="#E9EEF5">' . $cell . '</td>';
}
}
echo "</tr>\n";
}
mysql_free_result($result);
echo "</table>";
?>
Note that I use fetch_assoc to get the $name.
PS: <p/> does not exists and align and bgcolor and not valids but acceptable if this is a HTML code for an e-mail.

PHP Ranking function with TIES

So I have a function that takes a number and outputs it as a placement. How do I go about making the function take in consideration ties. I have a ranking database and this php code echos out rankings on a table. right now it ranks but it doesn't consider ties. How do i go about doing this
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
?>
<?php
$link = mysqli_connect("localhost", "citricide", "321213123Lol", "juneausmashbros");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM rankings ORDER BY points DESC";
$result = mysqli_query($link, $query);
echo '<article class="content grid_6 push_3">';
echo '<h1>';
echo 'Project M Summer Ranbat Rankings';
echo '</h1>';
echo '<section>';
echo '<center>';
echo '<table style="width:400px" class="rankslist">';
echo '<tr>';
echo '<th width="15%"><b>Rank</b></th>';
echo '<th width="45%"><b>Name</b></th>';
echo '<th width="45%"><b>Alias</b></th>';
echo '<th width="15%"><b>Points</b></th>';
echo '</tr>';
$ass = 0;
while($row = $result->fetch_array()) {
$ass++;
echo '<tr>';
if ($ass == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($ass == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($ass == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($ass);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
echo '</table>';
echo '</center>';
echo '</section>';
echo '</article>';
?>
It seems like you need additional variables to track the rank and the previous value. By doing so, you can handle ties.
For example:
$ass = 0; // current record count
$rank = 0; // rank
$last_points = NULL; // variable to store last ranked value
while($row = $result->fetch_array()) {
$ass++;
// check if value changes and reset rank if it does
if ($row['points'] !== $last_points) {
$rank = $ass;
$last_points = $row['points'];
}
echo '<tr>';
if ($rank == 1) {
echo ' <center><td><B><font color=#FFD700>';
} else if ($rank == 2) {
echo ' <center><td><B><font color=#CCCCCC>';
} else if ($rank == 3) {
echo ' <center><td><B><font color=#cd7f32>';
} else {
echo '<td>';
}
echo addOrdinalNumberSuffix($rank);
echo ' </font></B</td></center>';
echo ' <td>'.$row['name'].'</td>';
echo '<td>'.$row['alias'].'</td>' ;
echo '<td>'.$row['points'].'</td>';
echo '</tr>';
}
So say your points looked like this:
100
100
90
80
The $rank value would be:
1
1
3
4

PHP members page carrying down to new line

I have a page on my site that shows a member directory. I want the members to be listed 3 per row, before it goes to the next row. The code I have, does this for the very first row - but on the second row, its all on one line and doesnt carry down.
The profiles are showing up like this:
uuu
uuuuuuuuuuuuuuuuuuuuuuuuuuu
When they should be doing this:
uuu
uuu
uuu
uuu
This is what my code looks like:
<table>
<tr>
<td colspan="4"><h1>Member Directory</h1></td></tr>
<tr>
<td>
<?php
while($row = mysql_fetch_array($result)) {
if (empty($row['profile']) === false){
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td><td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'] . "<br />";
echo '</td><td>';
if ($i++ == 2) echo '</td></tr><tr><td>';
}
?>
</td>
</tr>
</table>
Any help would be greatly appreciated, thanks!
Use
if (++$i % 3 == 0) echo '</td></tr><tr><td>';
Explanation:
First of all ++$i first increments $i, and then uses it in whatever is next, this makes for more readable code.
Second, the % is the modulus, which means it sortof subtracts 3 from $i until it is not possible anymore. E.g. 9 % 3 == 0, and 11 % 3 == 2 and so on. This means we know that we have printed 3 rows whenever $i % 3 equals 0.
try this one
<table>
<tr>
<td colspan="4"><h1>Member Directory</h1></td>
</tr>
<?php
$count=0;
while($row = mysql_fetch_array($result))
{
$count+=1;
if($count%3==1)
{
echo '<tr>';
}
echo '<td>';
if (empty($row['profile']) === false){
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td>';
echo '<td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'] . "<br />";
echo '</td>';
if($count%3==0)
{
echo '</tr>';
}
}
if($count%3!=0)
{
echo '</tr>';
}
?>
</table>
You didn't reset the value of $i, so it kept increasing; another issue is that if you have only seven items, the last row should have four empty cells. So the loop condition needs to be augmented with a row completion status:
$i = 0;
while (($row = mysql_fetch_array($result)) !== false || $i != 0) {
if ($i == 0) {
echo '<tr>'; // start of new row
}
if ($row !== false) {
echo '<td>';
if (empty($row['profile'])) {
echo '<img src="', $row['profile'], ' "width="125">';
} else {
echo '<img src="../../images/template/avatar.png">';
}
echo '</td><td>';
echo '' . ucfirst($row['username']) . '<br />';
echo "Location: " . $row['location'];
echo '</td>';
} else {
echo '<td></td><td></td>'; // no more data
}
$i = ($i + 1) % 3; // advance
if ($i == 0) {
echo '</tr>'; // end of the row
}
}

How to print an array of links in PHP

Need some php help in figuring out how use this array I created, but first of all I'm not sure if I done this right?? Its an array with names and href links that I would like to map for given server. Pls let me know if I constructed this properly:
$server_array = array(
'server1.domain' => array(
'href' => 'https://server1.domain.com:8080'
),
'server2.domain' => array(
'href' => 'https://server2.domain.com:8080'
),
'server3.domain' => array(
'href' => 'https://server3.domain.com:9999'
...
);
I want to map the data from my key Server to one of these links. So far, I've created a table with the server names and all I want to do is map that server name to one of the above hyper links within the table.
Can someone show me how to tweak my print code to do this? Thanks.
Code to display the table with servername:
$keys = array('Server', Target','Set','Time', 'Length','Size','Status');
echo '<table id="stats_1"><tr>';
foreach ($keys as $column)
echo '<th>' . $column . '</th>';
echo '</tr>';
$counter=0;
foreach ($data as $row){
$counter ++;
$class = $counter % 2 === 0 ? 'alt1' : 'alt2';
echo '<tr class="' . $class . '">';
foreach ($keys as $column){
if (isset($row[$column])){
echo '<td>' . $row[$column] . '</td>';
} elseif ($column == 'Status') {
echo '<td> Check Logs </td>';
} elseif ($column == 'Length') {
echo '<td> n/a </td>';
} elseif ($column == 'Size') {
echo '<td> n/a </td>';
} else {
echo '<td> </td>';
}
}
}
echo '</table>';
If I got the question correctly, I would create the array like:
$server_array = array(
'server1.domain' => 'https://server1.domain.com:8080',
'server2.domain' => 'https://server2.domain.com:8080',
...
);
And for creating the link you would have to do (assuming $row['Server'] would contain the name like 'server5.domain'):
if ($column == 'Server'){
echo '<td> ' . $row[$column] . '</td>';
}
Full code:
$keys = array('Server', 'Target','Set','Time', 'Length','Size','Status');
echo '<table id="stats_1"><tr>';
foreach ($keys as $column) {
echo '<th>' . $column . '</th>';
}
echo '</tr>';
$counter=0;
foreach ($data as $row){
$counter ++;
$class = $counter % 2 === 0 ? 'alt1' : 'alt2';
echo '<tr class="' . $class . '">';
foreach ($keys as $column){
if (isset($row[$column])){
if ($column == 'Server'){
echo '<td> ' . $row[$column] . '</td>';
} else {
echo '<td>' . $row[$column] . '</td>';
}
} elseif ($column == 'Status') {
echo '<td> Check Logs </td>';
} elseif ($column == 'Length') {
echo '<td> n/a </td>';
} elseif ($column == 'Size') {
echo '<td> n/a </td>';
} else {
echo '<td> </td>';
}
}
}
echo '</table>';

Categories