Generate a table with PHP - php

I'm trying to generate a table in PHP.
I need this table has 365 cells.
Each row need to contains 30 cells.
How is it possible please?
Actually, I have:
echo '
<table class="table">
';
$dates = getDatesFromRange('2017-01-01', '2018-01-01');
$i=1;
$limit=30;
// $dates contains an array of 365 dates
foreach($dates as $date){
if($i <= $limit) {
echo '<td width="20">'.-.'</td>';
$i++;
}
else {
echo '<tr><td width="20">'.-.'</td></tr>';
$i=1;
}
}
echo '
</table>
';

Use nested loops for this:
$cells_per_row = 30;
$rows = ceil(count($dates)/$cells_per_row);
echo '<table class="table">';
for($i=0;$i<$rows;$i++){
echo '<tr>';
for($u=0;$u<$cells_per_row;$u++){
if(!isset($dates[$i*$cells_per_row+$u])) // stop if end of array is reached
break;
echo '<td width="20">'.$dates[$i*$cells_per_row+$u].'</td>';
}
echo '</tr>';
}
echo '</table>';

Related

Playing around with Modulus Division

I'm trying out the modulus division with a foreach loop, and I'm having a bit trouble understanding it.
$counter = 0;
foreach($result as $row){
if(isset($row['username'])){
if (($counter) % 2 == 0){
echo "<tr class=\"r1\"><td class=\"center\">" . $row['username'] . "</td></tr>";
}
else{
echo "<tr class=\"r0\"><td class=\"center\">" . $row['username'] . "</td></tr>";
}
$counter++;
}
}
I want to output:
<tr class="r0">
<td>Bob</td>
<td>Daniel</td>
</tr>
<tr class="r1">
<td>Dylan</td>
<td>Bruce</td>
</tr>
But currently, with my loop, I'm outputting:
<tr class="r1">
<tdBob</td>
</tr>
<tr class="r0">
<td>Daniel</td>
</tr>
<tr class="r1">
<td>Dylan</td>
</tr>
<tr class="r0">
<td>Bruce</td>
</tr>
Can someone explain to me exactly how modulus division works? Thank you.
Here, you want to display two records in one row. Actually modulus division will return the remainder of the division. Try with:
$counter = 0;
$i=1;
foreach($result as $row){
if(isset($row['username'])){
if (($counter) % 2 == 0){ // that is the counter value/2 doesnot returns a remainder ie, divisible by 2, then create another row
if($i%2==0)
{
echo "<tr class=\"r1\">";
}
else
{
echo "<tr class=\"r0\">";
}
}
else{
echo "<td class=\"center\">" . $row['username'] . "</td>";
}
if (($counter) % 2 == 0){ // close the tr if the counter doesnot return remainder
echo "</tr>";
}
$counter++;
$i++;
}
}
I got this to work. My problem was that my array was multidimensional, so I converted it to a single array. Afterwards, I used array_chunks.
$chunks = array_chunk($l, 2);
$i=0;
foreach($chunks as $mychunk){
if($i%2== 0){
echo "<tr class=\"r0\">";
} else { echo "<tr class=\"r1\">"; }
$i++;
foreach($mychunk as $newchunk)
{
echo "<td class=\"center\">" . $newchunk . "</td>";
}
echo "</tr>";
}
For anyone looking to convert multidimensional arrays into single dimensional array:
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}

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

Not printing all rows in mysql table

I'm creating a movie database for private purposes. As a part of the database I want to be able to show the movies by sorting by genre, starting letter of movies or just show all.
I want to display the hits in a three column table until all rows in the database table have been printed.
For example:
Ice age 1 Ice age 2 Ice age 3
Die Hard 1 Die Hard 2 Die hard 3
What happens with the code below (Which is used when all movies should be shown) is that it stops after 39 rows even though I know it's 50 rows, mysql_num_rows() returns 50 and when I just printed the complete db table in 1 column I got 50 rows.
$counterone = 0;
$countertwo = 0;
if ($_movietype == 'showmeeverything')
{
$movieresult = mysql_query("SELECT url,title FROM movies ORDER BY title");
if(mysql_num_rows($movieresult) == 0)
{
nomovie();
}
echo '<p align="center">Go back</p>';
echo '<table border="1" cellspacing="2" cellpadding=2" align="center">';
echo '<tr><td colspan="3" align="center"><b>Title</b></td></tr>';
echo mysql_num_rows($movieresult);
while ($counterone < mysql_num_rows($movieresult))
{
$counterone++;
echo '<tr>';
while (($result = mysql_fetch_array($movieresult)) && $countertwo < 3)
{
echo '<td>';
echo '' . $result['title'] . '';
echo '</td>';
$countertwo++;
}
echo '</tr>';
$countertwo = 0;
}
echo '</table>';
echo '<p align="center"><a align="center" href="index.php">Go back</a></p>';
}
You're not incrementing $counterone in the right spot. You're counting table ROWS, but are working off number of records. $counterone should be inside the internal while($result) loop. And once it's there, $countertwo is redundant.
Try this instead:
$counter = 0;
while($row = mysql_fetch_array($movieresult)) {
if ($counter % 3 == 0)
echo '<tr>';
}
echo "<td> blah blah blah </td>";
if ($counter % 3 == 2) {
echo '</tr>';
}
$counter++;
}
Try this:
$counterone = 0;
$countertwo = 0;
if ($_movietype == 'showmeeverything')
{
$movieresult = mysql_query("SELECT url,title FROM movies ORDER BY title");
if(mysql_num_rows($movieresult) == 0)
{
nomovie();
}
echo '<p align="center">Go back</p>';
echo '<table border="1" cellspacing="2" cellpadding=2" align="center">';
echo '<tr><td colspan="3" align="center"><b>Title</b></td></tr>';
echo mysql_num_rows($movieresult);
$numrows = mysql_num_rows($movieresult);
while ($counterone < $numrows)
{
$counterone++;
echo '<tr>';
while (($result = mysql_fetch_array($movieresult)) && $countertwo < 3)
{
echo '<td>';
echo '' . $result['title'] . '';
echo '</td>';
$countertwo++;
}
echo '</tr>';
$countertwo = 0;
}
echo '</table>';
echo '<p align="center"><a align="center" href="index.php">Go back</a></p>';
}

Populate an html table columwise with mysql data

I have a MySQL query that returns data using PHP.
My problem is that I need to populate my html table (with 3 columns) with the data returned by the query but the data should be populated Columnwise.
Like first the first column should be populated .. then the second and finally the third one.
Also I would like to know that is it possible to do so for an unlimited set of data?
Following the screen shot of the desired layout
you can use while.
<table>
$sql=mysql_query("select * from table");
while($s=mysql_fetch_array($sql))
{
$x=$s["x"];
<tr>
<td ><?php echo $x; ?></td>
<td ><?php echo $y; ?></td>
<td ><?php echo $z; ?></td>
</tr>
}
</table>
guybennet's answer is correct but if you want it to work for an unlimited amount of columns you could do this: (I also threw in some column headers for readability)
echo '<table>';
$counter = 0;
$result = mysql_query("select * from table");
while($row = mysql_fetch_array($result)) {
$counter++;
if($counter == 1) {
echo '<tr>';
foreach($row as $key => $val) {
echo "<th>$key</th>";
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}
echo '</table>';
Also of course you should use mysqli or PDO I'm just showing a quick example.
If you don't care about how it's organized, you can try something like this:
echo "<table><tr>";
$i=0;
while($row = mysql_fetch_array($sql))
{
echo "<td>".$row[0]."</td>\n";
$i++;
if($i==3)
{
echo "</tr>\n<tr>";
$i=0;
}
}
echo "</tr></table>";
Otherwise, I'd suggest putting it all into an array and then putting it into the table.
$data = array();
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
$itemsAmount = count($data);
$ceilAmount = ($itemsAmount - $itemsAmount % 3) / 3;
$lastAmount = $itemsAmount % 3;
$firstArray = array_slice($data, 0, $itemsAmount);
$secondArray = array_slice($data, 0, $itemsAmount*2);
$thirdArray = array_slice($data, 0, $lastAmount);
$output = "<table>";
foreach ($data as $key => $value) {
$output .= "<tr>";
$output .= "<td>" . $firstArray[$key][0] . "</td>";
$output .= "<td>" . $secondArray[$key][0] . "</td>";
if (empty($thirdArray[$key])) {
$str = '';
} else {
$str = $thirdArray[$key][0];
}
$output .= "<td>" . $str . "</td>";
$output .= "</tr>";
}
$output .= "</table>";
echo $output;
You need to check all the results returned, then print them as you won't print in order:
First get an array with all the results
<?php
$sql= mysql_query('SELECT * FROM table');
$num= mysql_affected_rows($sql);
$items = array();
$i=0;
while($item=mysql_fetch_array($sql)){
$items[++$i]=$item['data'];
}
Now start printing
int $num_rows;
$num_rows=$num%3;
echo '<table>';
for ($i=0;$i<$num_rows;$i++){
echo '<tr>';
for ($j=0;$j<2,$j++){
$n=$i+1+($j*$num_rows);
if($items[$n]!==null)
echo '<td>'.$items[$n].'</td>';
else
echo '<td></td>';
}echo '</tr>';
}echo'</table>';
?>

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