I have table with product_category and its has more than 20 categories and I want to display them in table format like below image
I like to place categories in 5 td then how I can be fixed towards tr in a table
Below is code I have tried, but its not giving the desired output
And below is the image that might be solution I needed
Below code
<table>
<?php
$fquery5 = mysql_query("select Cat_ID, Cat_Name from product_category where Active_Flag=1");
$count1 = mysql_num_rows($fquery5);
$hor_length = 5;
$ver_length = $count1 / $hor_length;
$data1 = mysql_fetch_row($fquery5);
for ($i = 0; $i <= $ver_length; $i++) {
echo "<tr>";
for ($j = $i + $hor_length; $j <= $count1; $j++) {
echo "<td>";
echo "Id : " . $data1[0] . " = " . $data1[1];
echo "</td>";
}
echo "</tr>";
}
?>
</table>
Added resultant output image answered by #DaveRandom
Try this (FIXED):
<?php
// Number of columns
$hor_length = 5;
// Do the query, get the number of rows in the result
$fquery5 = mysql_query("
SELECT Cat_ID, Cat_Name
FROM product_category
WHERE Active_Flag = 1
");
$numrows = mysql_num_rows($fquery5);
// Start of table
echo "<table>\n<tr>\n";
// Loop the results with a counter
for ($i = 1; $row = mysql_fetch_row($fquery5); $i++) {
// Every iteration echos a cell
echo "<td>Id : " . $row[0] . " = " . $row[1] . "</td>\n";
// If we're at the end of a row, echo a row break, unless it is the last result
if (!($i % $hor_length) && $i < $numrows) {
echo "</tr>\n<tr>\n";
}
}
// Right-pad the end row with empty cells
for ($i--; $i % $hor_length; $i++) {
echo "<td></td>\n";
}
// Echo the end of the table
echo "</tr>\n</table>";
See a working example (manually created the data array since I can't query a DB from codepad)
Related
I have a CSV file that has (dummy) data like this:
Mike Judge, Office Space, Comedy
Larry Wachowski, Matrix Zero, Action
Sofia Coppola, Lost In Translation, Drama
Ron Howard, A Beautiful Mind, Drama
Joe Biden, Your Big Hat, Sports
Barack Obama, The Stubborn Goat, Drama
Steve Smith, 2 Beautiful Ants, Suspense
Jared Hess, Napoleon Dynamite, Comedy
Jack Daniels, Field of Dreams, Drama
I need the 1st field sorted alphabetically by last name. That works.
Then I need to show the array in an HTML table and be able to set the number of columns to perhaps 5. I need each cell to hold one line from the CSV file, then move left to right filling the table.
Everything I've tried gets me almost there, but the table does not display properly - it has missing td tag or no in the last td.
Any help would be appreciated.
Here's what I have so far:
$file = fopen("dummy-list.csv", "r") or die('cannot open file');
// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);
// set # of table columns
$numCols = 4;
$i=0;
echo '<table border="1" align="center"><tr>' . "\n";
foreach( $rows as $rows2 )
{
if ($i % $numCols == 0 && $i != 0)
echo "</tr>\n<tr>"; // every time but the first
echo '<td>';
foreach( $rows2 as $key )
{
echo $key . '<br />';
$i++;
}
echo "</td>\n";
}
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
// end table
echo '</tr></table>' . "\n\n\n";
Stay with your code:
Change this:
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
For it:
$mod = $numCols-count($rows)%$numCols;
for($i=0;($i < ($mod) && $mod != $numCols);$i++)
echo '<td> </td>' . "\n";
And solve your problems!
You just need to modify your logic slightly. Currently, your script doesn't track which column your in, so it has no way of knowing how many cells to pad.
The biggest logical problem is:
while ($i++ % $numCols != 0)
echo '<td> </td>' . "\n"; // fill in empty cells
All that is doing is checking that the number of columns is devisable by $i. so, after $i gets to 3, it stops. (in this case 4/3 != 0)
The following works:
$file = fopen("dummy-list.csv", "r") or die('cannot open file');
// sort
$surnames = array();
$rows = array();
//build array of surnames, and array of rows
while (false != ( $row = fgetcsv($file, 0, ',') )) {
//extract surname from the first column
//this should match the last word before the comma, if there is a comma
preg_match('~([^\s]+)(?:,.*)?$~', $row[0], $m);
$surnames[] = $m[1];
$rows[] = $row;
}
//fclose($file);
//sort array of rows by surname using our array of surnames
array_multisort($surnames, $rows);
//print_r($rows);
// set # of table columns
$numCols = 4;
$i=0;
$cellpos = 0; //count columns
echo '<table border="1" align="center"><tr>' . "\n";
//use the amount of rows as a divisor
for($c=0; $c<Count($rows); $c++ )
{
if ($i % $numCols == 0 && $i != 0){
echo "</tr>\n<tr>"; // every time but the first
$cellpos=0; //reset our column position
}
echo '<td>';
//then, call each csv row explicitly
foreach( $rows[$c] as $key )
{
echo $key . '<br />';
$i++;
}
echo "</td>\n";
$cellpos++; //track our column position
}
while ($cellpos++ < $numCols)
echo '<td> </td>' . "\n"; // fill in empty cells
// end table
echo '</tr></table>' . "\n\n\n";
I added $cellpos variable to count the td in each row, as your populating. It gets reset every time you start a new row. if you track that var through the script you will see my changes.
Additionally, if you want to do something more specific with those keys, you can call them directly instead of just looping over the row. Just change the code between <td> tags.
echo '<td>';
//then, call each csv celldata explicitly
echo '<img src="'. $rows[$c][1] . '" /><br />' .$rows[$c][2] . '';
$i++;
echo "</td>\n";
You can use the MOD operator to check if you are at the end of a column and then end the row, and start a new one:
$cols = 4;
$count = count($rows);
$table_html ="<tr>";
for($i=0; $i < $count; ++$i){
$table_html.= '<td>' . implode("<br>", $rows[$i]) . '</td>';
if($i != 0 && ($i % $cols == 0)){
$table_html.="</tr>";
}
}
$table_html.="</tr>";
echo $table_html;
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--;
}
I have a small PHP script
<?php
$index = 1;
while($index <= 5) {
$qry="SELECT * FROM service_cost WHERE id_serv_cost=".$index;
echo "<br/>".$qry."<br/>";
$results=mysql_query($qry);
echo "<br/>".print_r($results)."<br/>";
$ligne=mysql_fetch_assoc($results);
echo "<br/>".print_r($ligne)."<br/>";
$coul='white';
if ( $t_price[1]==$index)
$coul='F4C6C6';
echo "<tr>".
"<td style='padding-right:10px;font-weight:bold;align=right>".$index."</td>".
"<td>".$ligne['min_call']."</td>".
"<td>$".sprintf("%4.2f",$ligne['positive_answer_price'])."</td>".
"<td>$".sprintf("%4.2f",$ligne['random_caller_id_price'])."</td>".
"<td>$".sprintf("%4.2f",$ligne['voice_message_price'])."</td>".
"<td>$".sprintf("%4.2f",$ligne['call_back_price'])."</td>".
"<td>$".sprintf("%4.2f",$ligne['unanswered_price'])."</td>".
"<td>$".sprintf("%4.2f",$ligne['transaction_fee'])."</td>".
"<td>$".sprintf("%4.2f",$ligne['transaction_cost'])."</td>".
"</tr>";
$index = $index + 1;
}
?>
I see my "echo $qry" only 3 times and in my table there is only 2 rows
the $index in the "echo $qry" are (1,3,5) but in the table, the displayed $index are (2,4)
In my DB there is 5 rows
I want an id column generated by php loop and I tried the code below.
This code is working but it skips first row. For e.g. if there are 153 rows, it shows only 152 rows because it skips first row and starts numbering from second row.
$i = 0;
$result = mssql_query ($sql);
$cell = mssql_fetch_array($result);
while ($i <= $cell & $cell = mssql_fetch_array($result))
{
$i = $i + 1;
echo "<tr><td>".$i."</td>";
echo "<td>".$cell[0]."</td>";
echo "<td>".$cell[1]."</td>";
echo "<td>".$cell[2]."</td>";
echo "<td>".$cell[3]."</td>";
echo "<td>".$cell[4]."</td>";
echo "<td>".$cell[5]."</td>";
echo "</tr>";
}
$cell = mssql_fetch_array($result);
^^^^^^^^^^^^^^^^^
fetches the first record
while ($i <= $cell & $cell = mssql_fetch_array($result))
^^^^^^^^^^^^^^^^^
fetches the second record
You're never outputting the first record you're fetching.
No idea what you're trying to do with that $i condition.
$i = 0;
$result = mssql_query ($sql);
//$record = mssql_fetch_array($result); - you don't need this
while ($cell = mssql_fetch_array($result)) //you dont need $i <= $cell
{
$i++; //$i = $i + 1;
echo "<tr><td>".$i."</td>";
echo "<td>".$cell[0]."</td>";
echo "<td>".$cell[1]."</td>";
echo "<td>".$cell[2]."</td>";
echo "<td>".$cell[3]."</td>";
echo "<td>".$cell[4]."</td>";
echo "<td>".$cell[5]."</td>";
echo "</tr>";
}
I'm guessing you probably want && instead of & here:
while ($i <= $cell & $cell = mssql_fetch_array($result))
I'm querying a database for names that are numbered 1-26 alphabetically. I have the following code, but since HTML is structured tr then td, the table appears alphabetically by row as opposed to by column. How can I make it appear in order by column?
$query = mysql_query("SELECT name FROM people WHERE main=1 ORDER BY id");
$i = 0;
while($result = mysql_fetch_array($query)) {
$name = $result['name'];
if ($i % 5 == 0) echo "<tr>\n";
echo "<td width=\"150\">";
echo "".$name."<br />";
echo "</td>\n";
$i++;
if ($i % 5 == 0) echo "</tr>\n";
};
alpha beta charlie
delta echo foxtrot
vs.
alpha charlie echo
beta delta foxtrot
Also, I'm open to reworking the code if there's a more efficient way.
You could just access the output array in strides. Compute how many rows you need as the number of results divided by 5, and use the row count as the stride.
$ncols = 5;
$nrows = $nresults / $ncols + ($nresults % $ncols == 0 ? 0 : 1);
for ($i = 0; $i < $nrows; $i++)
{
// start row
for ($j = 0; $k < $ncols; $j++)
{
// print $results[$nrows * $j + $i]
}
// end row
}
You'll have to transfer your query results into an array $results first. Since you'll have to know the total number of results, this is sort of mandatory, though I'd be curious if anyone has a solution that can work while fetching the results.
Update: See Justin's answer for a cool solution that grows the output while fetching the query results line by line. Since it's currently being worked on, here's a summary (credits to Justin):
$nresults = mysql_num_rows($query);
$ncols = 5;
$nrows = (int) ceil($nresults / $ncols);
$i = 0; $cols = array_fill(0, $nrows, "");
while ($result = mysql_fetch_array($query))
$cols[$i++ % $nrows] .= "<td>$result['name']</td>";
echo "<tr>" . implode("</tr><tr>", $cols) . "</tr>";
Edit:
After the discussion in the comments between myself, Kerrek SB and the OP bswinnerton, the following code seems to be the most effective:
$columns = 3;
$rowcount = mysql_num_rows($query);
$rows = ceil($rowcount / $columns);
$rowdata = array_fill(0, $rows, "");
$ctr = 0;
while ($result = mysql_fetch_array($query))
$rowdata[$ctr++ % $rows] .= '<td>'.$result['name'].'</td>';
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';
This will create three columns, filled vertically (my original answer would create three rows). It also properly initializes the array (preventing PHP warnings), yields a correct row count for result counts that aren't divisible by the column count, and incorporates Kerrek's clever "calc-row-in-the-subscript" trick.
Original Post:
You could use arrays and implode() This way, you only have to make one pass through your results:
$row = 0;
$rows = 3;
$rowdata = array();
while($result = mysql_fetch_array($query))
{
if ($row >= $rows) $row = 0;
$rowdata[$row++] .= '<td>'.$result['name'].'</td>';
}
echo '<tr>'.implode('</tr><tr>',$rowdata).'</tr>';