Print Function values inside a table? - php

How do I print the value of a function inside a table? I'm having a hard time trying to figure this out, looked it up in Google, watch some Youtube PHP tutorials and still came up with nothing, and there is also an error telling me that $cols, $rows, $rNumber is undefined. The output should look like a half pyramid.
<?php
do {
$rNumber = mt_rand(3, 11);
} while ($rNumber % 2 == 0);
echo '<strong>Looping Statements Exercises</strong>';
echo '<br>';
echo '<br>';
echo 'This page shows eight (8) figures programatically generated by looping statements. Number of rows are random odd integer between 3 and 11.';
echo '<br>';
echo '<br>';
echo '<table border = "1">';
echo '<tr>';
echo '<td colspan = "4"><center>Size:<strong>', $rNumber, ' x ', $rNumber, '</strong>';
echo '</tr>';
echo '<tr>';
echo '<td> Figure A';
echo '<td> Figure B';
echo '<td> Figure C';
echo '<td> Figure D';
echo '</tr>';
echo '<tr>';
echo '<td> Figure A here';
echo '<td>', figure_b($cols, $rows), '</td>';
echo '<td> Figure C here';
echo '<td> Figure D here';
echo '</tr>';
echo '<tr>';
echo '<td> Figure E';
echo '<td> Figure F';
echo '<td> Figure G';
echo '<td> Figure H';
echo '</tr>';
echo '<tr>';
echo '<td> Figure E here';
echo '<td> Figure F here';
echo '<td> Figure G here';
echo '<td> Figure H here';
echo '</tr>';
function figure_b($rows, $cols)
{
if ($rNumber == 5) {
for ($rows = 0; $rows <= 5; $rows++) {
for ($cols = 0; $cols <= 5; $cols++) {
return $cols;
}
return $rows;
}
}
}
echo '</table>';

Your function:
function figure_b($rows, $cols)
{
if($rNumber == 5)
{
for($rows = 0; $rows<=5; $rows++)
{
for ($cols = 0; $cols<=5; $cols++)
{
return $cols;
}
return $rows;
}
}
}
is completely wrong.
It should be rather:
function figure_b($rNumber)
{
if ($rNumber == 5) {
for ($rows = 0; $rows <= 5; $rows++) {
for ($cols = 0; $cols <= 5; $cols++) {
echo $cols.' ';
}
echo $rows.'<br />';
}
}
}
If you want to display anything inside your table and use rNumber variable (it seems there's no need to pass $rows and $cols variables here)
However your code is really bad, you should not mix PHP code and HTML code that way. If you need to you should move some part of your code to other file and not use so many echo because it also affects your performance.

you can begin by trying to changhe this
$rNumber = mt_rand(3,11);
}while ($rNumber % 2 == 0);
to this :
$rNumber = mt_rand(3,11);
while ($rNumber % 2 == 0);
and your function to :
function figure_b($rNumber)
{
if($rNumber == 5)
{
for($rows = 0; $rows<=5; $rows++)
{
for ($cols = 0; $cols<=5; $cols++)
{
echo $cols;
}
echo $rows;
}
}
}

<?php
do{
$rNumber = mt_rand(3,11);
}while ($rNumber % 2 == 0);
echo '<strong>Looping Statements Exercises</strong>';
echo '<br>';
echo '<br>';
echo 'This page shows eight (8) figures programatically generated by looping statements. Number of rows are random odd integer between 3 and 11.';
echo '<br>';
echo '<br>';
echo '<table border = "1">';
echo '<tr>';
echo '<td colspan = "4"><center>Size:<strong>',$rNumber,' x ',$rNumber,'</strong>';
echo '</tr>';
echo '<tr>';
echo '<td> Figure A';
echo '<td> Figure B';
echo '<td> Figure C';
echo '<td> Figure D';
echo '</tr>';
echo '<tr>';
echo '<td> Figure A here';
echo '<td>', figure_b(5, 5,$rNumber),'</td>';
echo '<td> Figure C here';
echo '<td> Figure D here';
echo '</tr>';
echo '<tr>';
echo '<td> Figure E';
echo '<td> Figure F';
echo '<td> Figure G';
echo '<td> Figure H';
echo '</tr>';
echo '<tr>';
echo '<td> Figure E here';
echo '<td> Figure F here';
echo '<td> Figure G here';
echo '<td> Figure H here';
echo '</tr>';
function figure_b($rows, $cols,$rNumber)
{
if($rNumber == 5)
{
for($rows = 0; $rows<=5; $rows++)
{
for ($cols = 0; $cols<=5; $cols++)
{
return $cols;
}
return $rows;
}
}
}
echo '</table>';
?>

Related

how to correctly accommodate the values?

I would like how to put the second result of the second query. the value is shows under row and I want that value is in front of the first result query.
The result should be shown where it is marked in red
$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
$bandera=0;
echo "<tr style=''>";
echo '<td>'.utf8_encode($fila["factura"]).'</td>';
echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
//
$id_documento=$fila["id_documento"];
$reporte->set('id_documento',$id_documento);
$reporte->contador();
$contador=$reporte->get('contador');
$id_documento=$fila["id_documento"];
$reporte2->set('id_documento',$id_documento);
$resultadosmov = $reporte2->movimientos();
while($fila2 = mysqli_fetch_array($resultadosmov))
{
echo'<tr>';
echo '<td></td>';
echo '<td></td>';
echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
echo '</tr>';
}
}
echo '</table>';
echo "</td></tr></table>";
Echo all the columns when processing the second query.
$resultados=$reporte->facturaCompleto();
while($fila = mysqli_fetch_array($resultados))
{
$bandera=0;
//
$id_documento=$fila["id_documento"];
$reporte->set('id_documento',$id_documento);
$reporte->contador();
$contador=$reporte->get('contador');
$id_documento=$fila["id_documento"];
$reporte2->set('id_documento',$id_documento);
$resultadosmov = $reporte2->movimientos();
if ($resultadosmov->num_rows > 0) {
while($fila2 = mysqli_fetch_array($resultadosmov))
{
echo "<tr>";
echo '<td>'.utf8_encode($fila["factura"]).'</td>';
echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
echo '<td>'.utf8_encode($fila2["no_parcialidad"]).'</td>';
echo '<td>'.utf8_encode($fila2["importe_total"]).'</td>';
echo '</tr>';
// Make 1st two columns blank in additional rows
$fila["factura"] = "";
$file["rfc_emisor"] = "";
}
} else {
echo "<tr style=''>";
echo '<td>'.utf8_encode($fila["factura"]).'</td>';
echo '<td>'.utf8_encode($fila["rfc_emisor"]).'</td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
}
}
BTW, what is the $bandera variable for? It's set but never used.
It would probably be even better if you could join the two queries, instead of doing queries in a loop.

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
}
}

PHP Sorting files in a table

Currently I have a table order by
A B C D
E F G H
but I would like to order the table by
A E
B F
C G
D H
Code:
for($i=0;$i<=count($aFiles);$i++)
{
if($i%5==0)
{
echo "</tr><tr>";
}
echo '<td><a>'.$aFiles[$i].'</a></td>';
}
echo '</tr>';
echo '</table>';
Files are already sorted a-z in $aFiles.
$aFiles = array('a','b','c','d', 'e', 'f', 'g');
$iColumnNumber = 2;
$iRowMaxNumber = ceil(count($aFiles) / $iColumnNumber);
$iTableRow = 0;
$iTableColumns = 1;
$aTableRows = array();
// make array with table cells
foreach ($aFiles as $sFile)
{
if ($iTableRow == $iRowMaxNumber)
{
$iTableRow = 0;
$iTableColumns++;
}
if (!isset($aTableRows[$iTableRow]))
{
$aTableRows[$iTableRow] = array();
}
$aTableRows[$iTableRow][] = '<td>' . $sFile . '</td>';
$iTableRow++;
}
// if there is odd number of elements
// we should add empty td elements
for ($iTableRow; $iTableRow < $iRowMaxNumber; $iTableRow++)
{
if (count($aTableRows[$iTableRow]) < $iTableColumns)
{
$aTableRows[$iTableRow][] ='<td>empty</td>';
}
}
// display table
echo '<table>';
foreach ($aTableRows as $aTableRow)
{
echo '<tr>';
echo implode('', $aTableRow);
echo '</tr>';
}
echo '</table>';
Simple Approach using HTML trick:
echo '<div class="tbl_group"><table>';
for($i=0;$i<=count($aFiles / 2);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
echo '<div class="tbl_group"><table>';
for($i=$aFiles / 2;$i<=count($aFiles);$i++)
{
echo '<tr>';
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo '</tr>';
}
echo '</tr>';
echo '</table></div>';
For the CSS:
.tbl_group {
float: left;
}
With this approach, 2 tables are built side-by-side. float: left CSS will auto adjust the position of the tables.
Assuming you know the number of rows you want, you don't need to resort anything, just add some logic in your loop that generates the <td>s :
$size = count($aFiles);
echo '<table><tr>';
for($i=0;$i<=ceil($size/2);$i++) {
if($i%2==0) {
echo '<td><a>'.$aFiles[$i].'</a></td>';
echo "</tr><tr>";
} else {
if(isset($aFiles[$i+floor($size/2)])) {
echo '<td><a>'.$aFiles[$i+floor($size/2)].'</a></td>';
}
}
}
echo '</tr></table>';
Example bellow also works with associative array + arrays with odd elements.
Code for associative AND indexed array :
$aFiles = ['test'=>"A","B",'c'=>"C","D","E","F",'g'=>"G","H",'iii'=>"I"];
$aKeys = array_keys($aFiles);
$aRows = ceil(count($aFiles) / 2);
echo '<table>';
for($i=0; $i < $aRows; $i++) {
echo
'<tr>' .
' <td>' . $aFiles[$aKeys[$i]] . '</td>' .
' <td>' . (isset($aKeys[$i+$aRows]) ? $aFiles[$aKeys[$i+$aRows]] : 'empty') . '</td>' .
'</tr>';
}
echo '</table>';
Code for ONLY indexed array :
$aFiles = ["A","B","C","D","E","F","G","H","I"];
$aRows = ceil(count($aFiles) / 2);
echo "<table>";
for($i=0; $i < $aRows; $i++) {
echo
"<tr>" .
" <td>" . $aFiles[$i] . "</td>" .
" <td>" . (isset($aFiles[$i+$aRows]) ? $aFiles[$i+$aRows] : "empty") . "</td>" .
"</tr>";
}
echo "</table>";
Output for both examples is identical :
<table>
<tr>
<td>A</td>
<td>F</td>
</tr>
<tr>
<td>B</td>
<td>G</td>
</tr>
<tr>
<td>C</td>
<td>H</td>
</tr>
<tr>
<td>D</td>
<td>I</td>
</tr>
<tr>
<td>E</td>
<td>empty</td>
</tr>
</table>
Not optimized, but this should more or less work:
$aFiles = array ("A","B","C","D","E","F","G","H","I","J","K","L","M","N",);
$rows = 4;
$columns = floor((count($aFiles)/$rows))+1;
echo '<table>';
for ($i=0;$i<$rows;$i++) {
echo '<tr>';
for ($j=0;$j<$columns;$j++) {
echo '<td>';
if (isset($aFiles[$i+$j*$rows]))
echo $aFiles[$i+$j*$rows];
else
echo " ";
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
You can change the number of rows if you want.
Try this one. Assume that your $aFiles contains a-z alphabetically.
for ($i = 0; $i < count($aFiles/2); $i++){
echo '<tr><td><a>'.$aFiles[$i].'</a><td><td><a>'.$aFiles[$i+13].'</a><td></tr>'
}

php foreachloop with html tables

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;
}

Applying different CSS to top 10 results of a query

The table below prints of the results of a query called $sqlStr3. It works fine. The query is set to return the top 25 results.
I would like to apply a unique CSS class (called "class1" for purposes of this question) to the top ten results in the query. How can I do this?
Thanks in advance,
John
$result = mysql_query($sqlStr3);
$count = 1;
$arr = array();
echo "<table class=\"samplesrec1edit\">";
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td class="sitename1edit2a">'.$count++.'.</td>';
echo '<td class="sitename1edit1">'.stripslashes($row["username"]).'</td>';
echo '<td class="sitename1edit2">'.number_format(($row["totalScore2"])).'</td>';
echo '</tr>';
}
echo "</table>";
use this:
$result = mysql_query($sqlStr3);
$count = 1;
$arr = array();
echo "<table class=\"samplesrec1edit\">";
while ($row = mysql_fetch_array($result)) {
if($count < 11){
echo '<tr class="top-10">';
}else{
echo '<tr class="non-top-10">';
}
echo '<td class="sitename1edit2a">'.$count++.'.</td>';
echo '<td class="sitename1edit1">'.stripslashes($row["username"]).'</td>';
echo '<td class="sitename1edit2">'.number_format(($row["totalScore2"])).'</td>';
echo '</tr>';
}
echo "</table>";
access the td of top10 using this css
.top-10 td{
//definitions
}
and access the td of non top10 lines with
.non-top-10 td{
//definitions
}
... class="...<?php if ($count <= 10) { ?> class1<?php } ?>" ...
And move the increment to the end of the loop.
you can do it in the server side via php like:
echo '<tr '.($count <=10 ? 'myclass' : '').' > ;
or in jquery in front side like:
$("someTableSelector").find("tr:lt(10)").addClass('myclass')
How about assigning each result from TOP10 a unique class called top_result_[n]?
while ($row = mysql_fetch_array($result)) {
echo '<tr'.($count++ <=10 ? ' class="top_result_'.$count.'"' : '').'>';
echo '<td class="sitename1edit2a">'.$count.'.</td>';
echo '<td class="sitename1edit1">'.stripslashes($row["username"]).'</td>';
echo '<td class="sitename1edit2">'.number_format(($row["totalScore2"])).'</td>';
echo '</tr>';
}
echo "</table>";
I'm not sure wether you want to apply ONE class for all 10 results or UNIQUE class for each from 10 results, as for the first case, the code would be:
while ($row = mysql_fetch_array($result)) {
echo '<tr'.($count++ <=10 ? ' class="top_result"' : '').'>';
echo '<td class="sitename1edit2a">'.$count.'.</td>';
echo '<td class="sitename1edit1">'.stripslashes($row["username"]).'</td>';
echo '<td class="sitename1edit2">'.number_format(($row["totalScore2"])).'</td>';
echo '</tr>';
}
echo "</table>";
Use CSS:
.samplesrec1edit tr:nth-child(-n+10) {
cssrule:value;
}
This technique only works in newer browsers however. The following link has compatibility charts.
http://reference.sitepoint.com/css/pseudoclass-nthchild

Categories