how to create table with dynamic column using php - php

Suppose there is a number of item in array.which may be odd or even like I have an array which contain item from a to z Now I want to display that item in table . But As you know That There are 23 alphabets I want to display these alphabets in table which contains only 5 column in the last you got only three alphabets I want to display them in table . In the last I want that there should be three column not 5.
Here is my code i could not get that what should i do?
But the problem I faced in the below code is that the second loop is not correct.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$count= sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){
echo "<tr>";
for($j=0;$j<=5;$j++){
echo "<td>'".$arr[$j]."'</td>";
}
echo "</tr>";
}
echo "</table>";
?>

My approach uses array_slice to take out pieces of the source and build rows:
$arr=array('a','b','c','d','e','f','g','h');
$offset = 0;
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
$offset += $num_columns;
$row_html = '';
foreach($slice as $n) $row_html .= "<td>$n</td>";
$table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;
Live demo

Try below code. Declaring number of column required in a variable, so which can be changed any time. closing the tr tag when loop count is same as number of columns to be displayed.
<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
echo "<td>'".$arr[$r]."'</td>";
if($r + 1 == $columnLength ) {
echo "</tr>";
}
}
echo "</table>";
?>

Related

Reflective pattern of numbers in rows and columns of html table using loops

I'm stuck trying to use nested loops to make a reflective pattern from numbers.
I've already tried, but the output looks like this:
|0|1|2|
|0|1|2|
|0|1|2|
This is my code:
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 3; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 3; $col++) {
$p = $col-1;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>
I expected this result:
|0|1|0|
|1|2|1|
|0|1|0|
Each columns' and rows' cell values must increment to a given amount then decrement to form a mirror / palindromic sequence.
First declare the square root of the of the table cell count. In other words, if you want a 5-by-5 celled table (25 cells), declare $size = 5
Since your numbers are starting from zero, the highest integer displayed should be $size - 1 -- I'll call that $max.
I support your nested loop design and variables are appropriately named $row and $col.
Inside of those loops, you merely need to make the distinction between your "counters" as being higher or lower than half of the $max value. If it is higher than $max / 2, you subtract the "counter" (e.g. $row or $col) from $max.
By summing the two potentially adjusted "counters" and printing them within your inner loop, you generate the desired pattern (or at least the pattern I think you desire). This solution will work for $size values from 0 and higher -- have a play with my demo link.
Code: (Demo)
$size = 5;
$max = $size - 1;
echo "<table>\n";
for ($row = 0; $row < $size; ++$row) {
echo "\t<tr>";
for ($col = 0; $col < $size; ++$col) {
echo "<td>" . (($row >= $max / 2 ? $max - $row : $row) + ($col >= $max / 2 ? $max - $col : $col)) . "</td>";
}
echo "</tr>\n";
}
echo "</table>";
Output:
<table>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>2</td><td>3</td><td>4</td><td>3</td><td>2</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
</table>
There are a lot of ways to achive that.
An easy way to do that is;
<?php
$baseNumber = 0;
echo "<table border='1' style='border-collapse: collapse'>";
for ($row = 0; $row < 3; $row++) {
echo "<tr>";
if ($row % 2 !== 0) {
$baseNumber++;
} else {
$baseNumber = 0;
}
for ($col = 0; $col < 3; $col++) {
echo "<td>" . ($col % 2 === 0 ? $baseNumber : $baseNumber + 1) . "</td>";
}
echo "</tr>";
}
echo "</table>";
this code will do what you want just call the patternGenerator function with the number of distinct numbers you want for your example these numbers are 3 (0,1,2).
the idea in this code is to use two for loops one that starts from the minimum number to the maximum one and the other one that starts after the maximum number decreasing to the minimum.
for example:
if min = 0 and max = 5
the first loop will print 0,1,2,3,4,5
and the second will print 4,3,2,1,0
and that's it.
at first, I created a function that creates just on row called rowGenerator it takes $min and $max as parameters and prints one row
so if we want to print a row like this: |0|1|0| then we will call this function with min = 0 and max = 1 and
if we want to print a row like this: |1|2|1| then we will call it with min = 1 and max = 2.
function rowGenerator($min, $max)
{
echo '<tr>';
for($i = $min; $i<=$max;$i++)
echo '<td>'.$i.'</td>';
for($i = $max-1; $i>=$min;$i--)
echo '<td>'.$i.'</td>';
echo '</tr>';
}
for now, we can print each row independently. now we want to print whole the table if we look at the calls we do for the rowGenerator function it will looks as follow:
(min = 0, max = 1),
(min = 1, max = 2) and
(min = 0, max = 1).
minimums are (0,1,0).
yes, it's the same pattern again. then we need two loops again one to start from 0 and increase the number until reach 1 and the other one to loop from 0 to 0.
and that's what happened in the patternGenerator function. when you call it with the number of distinct numbers the function just get the min that will always be 0 in your case and the max.
function patternGenerator($numberOfDistinct )
{
echo "<table border =\"1\" style='border-collapse: collapse'>";
$min = 0;
$max = $numberOfDistinct - 2;
for($i = $min;$i<=$max; $i++)
{
rowGenerator($i,$i+1);
}
for($i = $max-1;$i>=$min;$i--)
{
rowGenerator($i,$i+1);
}
echo '</table>';
}
this is the output of calling patternGenerator(3):
the output of calling patternGenerator(5):

php - get second row until last row in mysql

Using while loop, i can get all the result in the table and echo it into a html table.
But, i want to skip the first row, and echo the result starting from second row.
How can i do that?
This is my code.
$sql2="select * from table where year = '2015' and month = '2' order by month desc";
$result2=mysqli_query($conn,$sql2);
echo '<table>';
while($row2=mysqli_fetch_assoc($result2))
{
echo '<tr>';
echo '<th>'.$row2['acc_sth_date'].'</th>';
echo '<th>'.$row2['acc_sth_med_ori'].'</th>';
echo '<th>'.$row2['acc_sth_med_new'].'</th>';
echo '<th>'.$row2['acc_sth_operator'].'</th>';
echo '</tr>';
}
echo '</table>';
Help me please master. Thanks
You can achieve that in two ways.
You could use LIMIT statement in your sql query :
$sql2="select * from table where year = '2015' and month = '2' order by month desc LIMIT 1,100";
1 = Start at the 2nd row
100 = Returns a maximum of 100 rows
Add a condition in your while loop :
$firstRow = true;
while ($row2 = mysqli_fetch_assoc($result2))
{
if (true === $firstRow)
{
$firstRow = false;
continue;
}
// ... Rest of your code ...
}
You need to add a variable that is tested and set to true to not allow skipping next time:
$FirstRun=true;
while($row2=mysqli_fetch_assoc($result2))
{
if ($FirstRun){
$FirstRun = false;
}else {
echo '<tr>';
echo '<th>'.$row2['acc_sth_date'].'</th>';
echo '<th>'.$row2['acc_sth_med_ori'].'</th>';
echo '<th>'.$row2['acc_sth_med_new'].'</th>';
echo '<th>'.$row2['acc_sth_operator'].'</th>';
echo '</tr>';
}
}
Use the following code
$sql2="select * from table where year = '2015' and month = '2' order by month desc";
$result2=mysqli_query($conn,$sql2);
$row2=mysqli_fetch_assoc($result2);
$count = count($row2);
$i = 1;
echo '<table>';
while(i>=$count)
{
echo '<tr>';
echo '<td>'.$row2[i]['acc_sth_date'].'</td>';
echo '<td>'.$row2[i]['acc_sth_med_ori'].'</td>';
echo '<td>'.$row2[i]['acc_sth_med_new'].'</td>';
echo '<td>'.$row2[i]['acc_sth_operator'].'</td>';
echo '</tr>';
$i++;
}
echo '</table>';
It will display all rows except the first row.

php make html table rows equal

I am getting data from a my database. There is a admin panel also where people can add data to the database. The data gets on the page but some of the rows(<tr>) have less table data tags(<td>) than others. thus the table is not justified. Is there a way to add empty <td> to rows that need them? I have tried everything but i can't figure it out.
Picture on how the table looks at the moment:
The green numbers are the total sum of points but it's not clear because the table rows are jagged. How to fix tis?
If there is a jQuery solution that's also fine.
my code:
echo "<table class=\"zebra1\">";
echo "<th>N. </th>" . "<th>Team name: </th>" . "<th colspan=\"5\">Points: </th>" . "<th>Sum: </th>";
$numbering =1;
$query2 = $db->prepare("SELECT pisteet_1 As PIY, pisteet_2 as PIK, nimi As NIM, opisto As OPI, pisteet.kaupunki_id As KA FROM
pisteet INNER JOIN joukkueet ON joukkueet.id = pisteet.team_id INNER JOIN oppilaitokset ON oppilaitokset.opisto_id = joukkueet.opisto_id ORDER BY team_id ASC");
$query2->execute();
$results = $query2->fetchAll();
$tableD = array();
foreach ($results as $key) {
$tableD[$key['NIM']][] = array('PIY'=>$key['PIY'],'PIK'=>$key['PIK'],'KA'=>$key['KA'], 'OPI'=>$key['OPI']);
}
foreach($tableD as $teamN=>$values2){
//Echoing the Team name
echo "<tr class=\"all " . $values2[0]['KA'] . "\">";
echo "<td>" . $numbering . "</td>";
echo "<td>" . $teamN ."<span>" . $values2[0]['OPI'] ."</span></td>";
$sum1=0;
$sum2=0;
//Echoing the points
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
}
//Echoing the total sum of points
echo '<td class="Sum">'.$sum1.'/'.$sum2."</td>";
echo "</tr>";
$numbering ++;
}
echo '</table>';
I have a variable named: $colspancalculated that has the longest row: at the moment it stores the value 5.
Assuming you have a fixed number of columns (I assume this because you've got a colspan on your table header cell), you need to output the td elements as you are doing, or output blank cells if the records don't exist.
Consider something like this instead of your foreach:
// Echoing the points - as you mention in your comment, you've calculated
// the maximum column size as $colspancalculated - so you that as your upper limit
for($i = 0; $i < $colspancalculated; $i++) {
if(!isset($values2[$i]['PIY'])) {
// This record doesn't exist! Output a blank cell
echo '<td></td>';
continue;
}
// Otherwise, output the cell and do your calculations
echo '<td class="points">' . $values2[$i]['PIY'] . '/' . $values2[$i]['PIK'] . '</td>';
$sum1 += $values2[$i]['PIY'];
$sum2 += $values2[$i]['PIK'];
}
Instead of a foreach loop, use a for loop -- or, since you have to work with an iterator, anyway, just do:
$i = $numberOfColumnsLeftAtThisPointInYourScript
foreach($values2 as $v2){
echo "<td class=\"points\">" . $v2['PIY'] . "/" . $v2['PIK'] . "</td>";
$sum1 +=$v2['PIY'];
$sum2 +=$v2['PIK'];
$i--;
}
while($i > 0){
echo '<td> </td>';
$i--;
}

SQL output in multiple columns of unequal length

while($row = mysql_fetch_array($result41))
{
echo "<tr><td align='center'>" .$row['AdmitRollNo'] . " </td></tr>";
}
This returns around 50 Admit Roll Numbers in a single column of the table. But I need the output in 5 columns containing respectively 9, 10, 7, 11, 13 items.
How to proceed?
Using a modulus operator in PHP would be a good start. This should work:
// Set how many items per column.
$per_column = 9;
// Set the opening table row.
echo "<tr>";
// Setting the counter to 0.
$counter = 0;
while ($row = mysql_fetch_array($result41)) {
// Increment the counter by one.
$counter++;
// Do a modulus check between the counter & the per column value.
if ($counter % $per_column == 0) {
echo "</tr><tr>";
}
// Echo the table data columns.
echo "<td align='center'>" . $row['AdmitRollNo'] . " </td>";
}
// Set the closing table row.
echo "</tr>";
But you say 9, 10, 7, 11, 13 items per each column. A bit trickier. But I believe that can be done. And here is a concept I just whipped up. The idea is there is an array of per column values named $per_column_array plus a counter named $per_counter. The first time the modulus is reached, the counter is incremented by one, so the next $per_column_array value is grabbed.
// Set how many items per column.
$per_counter = 0;
$per_column_array = array(9, 10, 7, 11, 13);
// Set the opening table row.
echo "<tr>";
// Setting the counter to 0.
$counter = 0;
while ($row = mysql_fetch_array($result41)) {
// Increment the counter by one.
$counter++;
// Do a modulus check between the counter & the per column value.
if ($counter % $per_column_array[$per_counter] == 0) {
$per_counter++;
echo "</tr><tr>";
}
// Echo the table data columns.
echo "<td align='center'>" . $row['AdmitRollNo'] . " </td>";
}
// Set the closing table row.
echo "</tr>";
ANOTHER EDIT: Here is an attempt with columns. Please feel free to adjust but the basic concept is the values are placed in a nested <table> within the <table> structure you already have:
// Set how many items per column.
$per_counter = 0;
$per_column_array = array(9, 10, 7, 11, 13);
// Set the opening table row.
echo "<tr><td>";
echo "<table>";
while ($row = mysql_fetch_array($result41)) {
// Increment the counter by one.
$counter++;
// Do a modulus check between the counter & the per column value.
if ($counter % $per_column_array[$per_counter] == 0) {
$per_counter++;
echo "</table>";
echo "</td>";
echo "<td>";
echo "<table>";
}
// Echo the table data columns.
echo "<tr><td align='center'>" . $row['AdmitRollNo'] . " </td></tr>";
}
// Set the closing table row.
echo "</table>";
echo "</td></tr>";

mysql php columns

<?php
$say = array("ann","brenda","charles","david",
"edward","florence","geoff","harry",
"ingrid","james","kelly","liam");
$columns = 5;
for ($p=0; $p<count($say); $p++) {
// Start of table or line?
if ($p==0) { // Start of table
print "<table border=0><tr>";
} elseif ($p%$columns == 0) { // Start of row
print "<tr>";
}
print "<td>".htmlspecialchars($say[$p])."</td>";
// End of table or line?
if (($p+1)%$columns == 0) { // End of row
print "</tr>";
}
if ($p==count($say)-1) { // End of table
$empty = $columns - (count($say)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
?>
The result:
ann brenda charles david edward
florence geoff harry ingrid james
kelly liam
I'm trying to do the same with mysql
so far i got
<?php
$con = mysql_connect("localhost","root","lol");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$nam=$row['nam'];
$columns = 3;
for ($p=0; $p<count($id); $p++) {
// Start of table or line?
if ($p==0) { // Start of table
print "<table border=0><tr>";
} elseif ($p%$columns == 0) { // Start of row
print "<tr>";
}
print "<td>".$nam."</td>";
// End of table or line?
if (($p+1)%$columns == 0) { // End of row
print "</tr>";
}
if ($p==count($nam)-1) { // End of table
$empty = $columns - (count($nam)%$columns) ;
if ($empty != $columns) {
print "<td colspan=$empty> </td>";
}
print "</tr></table>";
}
}
}
mysql_close($con);
?>
Result:
ann
brenda
charles
david
edward
florence
geoff
harry
ingrid
james
kelly
liam
Question: what's wrong?
Dabase table
id nam
1 ann
2 brenda
3 charles
4 david
5 edward
6 florence
7 geoff
8 harry
9 ingrid
10 james
11 kelly
12 liam
I'd suggest that you split your code into two distinct functions.
One function will read information from the database or the array, the other will format the output.
Right now, it looks an awful lot like you took your first chunk of code and put it into the middle of the while loop in the second piece.
MySQL is returning results to you, one result row at a time. So what you should do is collect all those results first and then print them out second (either that, or make a counter on the number of rows returned). In your second piece of code, you're treating each result row as you were the entire array of results in the first piece.
That is, the line while($row = mysql_fetch_array($result)) returns a single row from the table.
Because of this, the line $id=$row['id']; does not assign an array to $id.
Because of this, the line for ($p=0; $p<count($id); $p++) { iterates over a single item, resulting in what you're seeing.
My code still looks a little hackish, but it may give you an idea. I'm afraid I haven't tested it.
print "<table><tr>";
$p=0;
$columns=3;
while( $row = mysql_fetch_array($result) ) {
if ( $p>0 && ($p % $columns)==0 )
print "</tr><tr>";
print "<td>{$row['nam']}</td>";
$p++;
}
for(true;($p % $columns)!=0;$p++) //Finish off $p from above
print "<td> </td>";
print "</tr></table>";
To do this in a more modular way:
function display($stuff,$cols){
//Make sure the table is some multiple of $cols to eliminate special cases
//Hackish
while( (count($stuff) % $cols)!=0 )
$stuff.push_back(" ");
//Start table and first row, eliminating another special case
print "<table><tr>";
for($i=0;$i<count($stuff);$i++){
if($i>0 && ($i % $cols)==0)
print "</tr><tr>";
print "<td>{$stuff[$i]}</td>";
}
print "</tr></table>";
}
$names=array()
while( $row=mysql_fetch_array($result) )
$names.push_back($row['nam']);
display($names,5);

Categories