Ordering data in the table - php

I have three tables created by uploaded data from the previous file. I would like to insert data in defined places, so that each service is a separate record in the table and has a separate quantity and amount assigned.
My php function:
function listService()
{
$service_chcecked = $_POST['service_chcecked'];
$quantity = $_POST['quantity_chcecked'];
$net_price = $_POST['net_price_chcecked'];
for ($x = 0; $x < count($service_chcecked); ++$x) {
echo '<tr><td>id:' . $x . '</td><td>name:' . $service_chcecked[$x] . '</td>';
for ($y = 0; $y < count($net_price); ++$y) {
echo '<td>price:' . $net_price[$y] . '</td>';
for ($z = 0; $z < count($quantity); ++$z) {
echo '<td>quantity:' . $quantity[$z] . '</td>';
};
};
echo '</tr>';
}
}
And my html place:
<div class='services'>
<table>
<tr>
<th><span>NO.</span></th>
<th><span>Service name</span></th>
<th><span>Net price</span></th>
<th><span>Quantity</span></th>
</tr>
<?php listServiceName(); ?>
</table>
</div>
Now it displays to me this way, with repeated data at the end :/
broken table

That's because you are nesting your for loops. You create the <tr> and the "id" and "name" <td> for each item in service_chcecked. Then you create a "price" <td> for each service_chcecked * net_price_chcecked. And your 3rd nested loop creates a "quantity" column for each service_chcecked * net_price_chcecked * quantity_chcecked. That's why you end up with that broken table. It depends on how you receive the POST data, but if your three arrays always have the same length, you could do it all in one loop:
function listService()
{
$service_chcecked = $_POST['service_chcecked'];
$quantity = $_POST['quantity_chcecked'];
$net_price = $_POST['net_price_chcecked'];
for ($x = 0; $x < count($service_chcecked); ++$x) {
echo '<tr><td>id:' . $x . '</td><td>name:' . $service_chcecked[$x] . '</td>';
echo '<td>price:' . $net_price[$x] . '</td>';
echo '<td>quantity:' . $quantity[$x] . '</td>';
echo '</tr>';
}
}

Its hard to understand whats happening but less is more and try not to mix your data & html inside your function its going to confuse you later on.
<?php
$services = $_POST['service_checked'];
$qtys = $_POST['quantity_checked'];
$prices = $_POST['net_price_checked'];
?>
<div class='services'>
<table>
<tr>
<th>NO.</th>
<th>Service name</th>
<th>Net price</th>
<th>Quantity</th>
</tr>
<? foreach($services as $k=>$service){?>
<tr>
<td><?=$k?></td>
<td><?=$service?></td>
<td><?=$qtys[$k]?></td>
<td><?=$prices[$k]?></td>
</tr>
<? }?>
</table>
</div>

Related

how to put sql data into an html table

I am trying to put my SQL data into an HTML data, this is the code I have so far but it does not work yet. I have tried to put HTML into my PHP code I am wondering whether I should do it the the other way round(put PHP into HTML), any reply greatly appreciated
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>";
echo"<td>" . $AE_events ['eventTitle'] . "</td>;
echo"<td>" . $AE_events ['eventDescription'] . "</td>;
echo"<td;>" . $AE_events ['eventStartDate'] . "</td>;
echo"<td>" . $AE_events ['eventEndDate'] . "</td>;
echo"<td>" . $AE_events ['eventPrice'] . "</td>;
$AE_eventTitle = $rowObj->eventTitle;
$AE_eventDescription = $rowObj->eventDescription;
$AE_eventStartDate = $rowObj->eventStartDate;
$AE_eventEndDate = $rowObj->eventEndDate;
$AE_eventPrice = $rowObj->eventPrice;
echo "<div> $AE_eventTitle<br> $AE_eventDescription<br>
$AE_eventStartDate<br>
$AE_eventEndDate<br> $AE_eventPrice<br> </div>";
}
If you want to draw a table out of data in PHP, you can have to use nested loops. The first loop manages the rows and the nested one manages the columns. Example :
$data = [
[1, 3, 5],
[2, 4, 6]
];
print "<table>";
for ($i = 0; $i < count($data); $i++) {
$row = $data[$i];
print "<tr>";
for ($k = 0; $k < count($row); $k++) {
print "<td>{$row[$k]}</td>";
}
print "</tr>";
}
print "</table>";
Outputs:
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
</tr>
</table>

Dynamically generate table using PHP

I know this has been asked before and I have got it working using the following code:
<?php
$maxcols = 8; $i = 0;
echo "<table id='table1'><tr>";
foreach ($id as $k => $v) {
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols) { $i = 0; echo "</tr><tr>"; }
} $i++;
while ($i <= $maxcols) {
$i++; echo "<td></td>";
}
echo "</tr></table>";
?>
This results in a table that looks like this :
I'd like to add headers to this so the end result looks like this:
I'd like to do it dynamically so if I create a table that is only 5 columns wide I'd get on the first header row ID01 - ID05 and on the second header row ID06 - ID10
I want to limit the header ID values to be no more than $maxid any extra header fields should be blank, like this : If $maxid = 12; then :
I need the header rows are made as follows and not using <TH>
<td class="mark">
I'm using some javascript to allow the movement of cell data.
The class is used to set the formatting on the header and stop items from being dragged into the fields.
Can anyone point me in the right direction on how to do this.
This should help you.
$maxcols = 8;
$maxid = 12;
$startid = 1;
echo "<table id='table1'>\n";
for ($i = 1;$i<=ceil($maxid/$maxcols);$i++) {
echo "<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
if ($startid <= $maxid)
echo " <td class='mark'>ID".$startid++."</td>\n";
else
echo " <td> </td>\n";
echo "</tr>\n<tr>\n";
for ($j=1;$j<=$maxcols;$j++)
echo "<td>Content</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Generates
<table id='table1'>
<tr>
<td class='mark'>ID1</td>
<td class='mark'>ID2</td>
<td class='mark'>ID3</td>
<td class='mark'>ID4</td>
<td class='mark'>ID5</td>
<td class='mark'>ID6</td>
<td class='mark'>ID7</td>
<td class='mark'>ID8</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td class='mark'>ID9</td>
<td class='mark'>ID10</td>
<td class='mark'>ID11</td>
<td class='mark'>ID12</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</table>
try this. It will work in the same way as you desired
<?php
$id= array("1","2","3","4","5","6","7","8","9","10","11","12");
$maxcols = 8; $i = 0;$j=0;$t=0;$s=0;
$maxid = count($id);
echo "<table id='table1'><tr>";
foreach ($id as $k => $v)
{
if($t == 0)
{
while ($t <= $maxcols-1) {
if($s < $maxid)
{
$s++;$t++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$t++;$s++;
}
}
echo "</tr><tr>";
}
else
{
}
echo "<td id='0'><div id='{$k}' class='drag t1'>{$v}</div></td>"; $i++;
if ($i == $maxcols)
{
echo "</tr><tr>";
if($j == 0)
{
while ($j <= $maxcols-1) {
if($s < $maxid)
{
$s++;$j++; echo "<td class='mark'>id$s</td>";
}
else
{
echo "<td class='mark'></td>";$j++;$s++;
}
}
echo "</tr><tr>";
}
$i=0;
}
}
echo "</tr></table>";
?>
Output
Hi You can Use My Library:
class generate{
private $row = "<tr>{columns}</tr>";
private $td = "<td {attr}>{data}</td>";
private $attributeTR="";
private $attributeTD="";
private $tdBuilder="";
public function addCol($ColumValsArr=array("class='motota'"=>"Example")){
foreach($ColumValsArr as $key=>$val){
$newCol = str_replace("{data}",$val,$this->td);
$newCol = str_replace("{attr}",$key,$newCol);
$this->tdBuilder .= str_replace("{data}",$key,$newCol);
}
}
public function getRow(){
return str_replace("{columns}",$this->tdBuilder,$this->row);
}
}
<?php
function TableFunc($Data)
{
$Table = "<table>" . PHP_EOL;
foreach ($Data as $tags => $array) {
$Table .= "<$tags>" . PHP_EOL;
foreach ($array as $thead) {
$tag=$tags==="tbody"?"td":"th";
$Table .= "<tr>" . PHP_EOL;
if (is_array($thead)) {
foreach ($thead as $theadItem) {
if (is_array($theadItem))
$Table .= "<$tag colspan='$theadItem[1]'>$theadItem[0]</$tag>" . PHP_EOL;
else
$Table .= "<$tag>$theadItem</$tag>" . PHP_EOL;
}
}
$Table .= "</tr>" . PHP_EOL;
}
$Table .= "</$tags>" . PHP_EOL;
}
$Table .= "</table>" . PHP_EOL;
return $Table;
}
$Data = array(
"thead" => [
[["GENEL BİLGİ", 2], ["KALORİMETRE (ISINMA)", 2], ["HESAPLAMA", 2]],
["NO", "AD SOYAD", "FARK", "TUTAR", "OKUMA", "ÖDENECEK"]
],
"tbody"=>array(
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
array("1","MURAT DURAN","100","100.00","10.00","110.00"),
),
"tfoot" => [["NO", "AD SOYAD", "M2", "MAHSUP", "SAYAÇ", "15°", "FARK", "TUTAR", "ORTAK ALAN", "EKSTRA", "MUAFİYET", "OKUMA", "ÖDENECEK"]]
);
echo TableFunc($Data);

Creating a table that multiplies height by weight

How would I create a table that multiples height by weight?
I have no idea how to figure it out!
I am trying to create a BMI calculator.
// collect values from a form sent with method=get
$min_weight = mysql_real_escape_string($_GET["min_weight"]);
$max_weight = mysql_real_escape_string($_GET["max_weight"]);
$min_height = mysql_real_escape_string($_GET["min_height"]);
$max_height = mysql_real_escape_string($_GET["max_height"]);
?>
<table>
<tr>
<td>Key:</td>
<td class="good show">Healthy (20-25)</td>
<td cla ss="warning show">Overweight (25-30)</td>
<td class="bad show">Unhealthy ( -20 or 30+)</td>
</tr>
</table>
<table border="1">
<?php
echo "<tr><td>Height →<br>Weight ↓</td>";
for ( $i = $min_height; $i <= $max_height; $i+=5 )
{
echo "<td>{$i}</td>";
}
echo "</tr>";
for ( $j = $min_weight; $j <= $max_weight; $j+=5 )
{
echo "<tr>";
echo "<td>{$j}</td>";
echo "</tr>";
}
This should do the job, i've also put some isset()'s:
<?php
// collect values from a form sent with method=get
$min_weight = isset($_GET["min_weight"]) ? mysql_real_escape_string($_GET["min_weight"]):0;
$max_weight = isset($_GET["max_weight"]) ? mysql_real_escape_string($_GET["max_weight"]):0;
$min_height = isset($_GET["min_height"]) ? mysql_real_escape_string($_GET["min_height"]):0;
$max_height = isset($_GET["max_height"]) ? mysql_real_escape_string($_GET["max_height"]):0;
?>
<table>
<tr>
<td>Key:</td>
<td class="good show">Healthy (20-25)</td>
<td class="warning show">Overweight (25-30)</td>
<td class="bad show">Unhealthy ( -20 or 30+)</td>
</tr>
</table>
<?php
$table = '<table border="1">';
$table .= '<tr><td>Height →<br>Weight ↓</td>';
for ($i = $min_height;$i <= $max_height;$i += 5){
$table .= "<td>$i</td>";
}
$table .= "</tr>";
for($j = $min_weight; $j <= $max_weight;$j += 5){
$table .= "<tr><td>$j</td>";
for ($i = $min_height;$i <= $max_height;$i += 5){
$table .= '<td>'. $i * $j .'</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
?>
Even though this works is it wrong to have the table border outside of the php tags?
<table>
<tr>
<td>Key:</td>
<td class="good show">Healthy (20-25)</td>
<td class="warning show">Overweight (25-30)</td>
<td class="bad show">Unhealthy ( -20 or 30+)</td>
</tr>
</table>
<table border="1">
<?php
echo "<tr><td>Height →<br>Weight ↓</td>";
for ( $j = $min_height; $j <= $max_height; $j+=5 )
{
echo "<td>{$j}</td>";
}
for ( $i = $min_weight; $i <= $max_weight; $i+=5 )
{
echo "<tr><td>{$i}</td>";
for ( $j = $min_height; $j <= $max_height; $j+=5 )
{
$var = number_format(($i)/(($j/100)*($j/100)),'2','.','');
{
echo "<td class='warning'>";
}
echo $var;
echo "</td>";
}
echo "</tr>";
}
?>
</table>

Unexpected output when comparing database column to variable

I have code which retrieves information about players from a MySQL database. I want to apply a special case to the HTML output if their ranking changes. I want it to look like this: http://i27.tinypic.com/f406tz.png
But i cant get it to be like i want, instead it prints the rank on every row:
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = "<tr><td> </td>\n";
}
echo " <td>$g->name</td></tr>\n";
}
What I want:
<tr>
<td>One</td>
<td>Kraven the Hunter</td>
</tr>
<tr>
<td> </td>
<td>Kull the Conqueror</td>
</tr>
<tr>
<td> </td>
<td>Zazi The Beast</td>
</tr>
<tr>
<td>Vice-leader</td>
<td>Igos du Ikana</td>
</tr>
<tr>
<td> </td>
<td>Saint Sinner</td>
</tr>
<tr>
<td> </td>
<td>Midvalley the Hornfreak</td>
</tr>.......................
What I get:
<tr><td>One</td>
<td>Tester</td></tr>
<tr><td>One</td>
<td>Kraven the Hunter</td></tr>
<tr><td>One</td>
<td>Kull the Conqueror</td></tr>
<tr><td>One</td>
<td>Zazi The Beast</td></tr>
<tr><td>Vice-Leader</td>
<td>Midvalley the Hornfreak</td></tr>
<tr><td>Vice-Leader</td>
<td>Saint Sinner
</td></tr>
<tr><td>Vice-Leader</td>
<td>Igos du Ikana</td></tr>
$old_rank is never equal to $g->rankname because the way you are setting $old_rank, it will contain HTML tags, and the $g->rankname that you get from the DB will never have HTML tags.
Try changing your if statement to something like this:
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = $g->rankname;
} else {
echo "<tr><td> </td>\n";
}
It prints the rank name if it's a new rank name, else it prints empty space.
The following (notwithstanding typos) separates out the display logic from the database loop. This has the advantages:
- You don't need to depend on the order of the results returned
- You don't need to maintain dodgy logic (like 'old_rank')
- You can display them more nicely (with a rowspan for repeated ranks
I believe the total code is more compact too.
// fill ranks array
$ranks = array();
while ( $g = mysql_fetch_object($q) ) {
if ( !in_array($g->rankname, $ranks) ) {
$ranks[htmlentities($g->rankname)] = array();
}
$ranks[$g->rankname][] = htmlentities($g->name);
}
// do other program logic here
// end of program
?>
<!-- display the page -->
<table>
<tr>
<th>Rank</th><th>Users</th>
</tr>
<?php foreach($ranks as $rankName => $userList): ?>
<tr>
<td rowspan="<?php echo (string)sizeof($userList); ?>">
<?php echo $rankName; ?>
</td>
<td> <?php echo implode('</td></tr><tr><td>', $userList); ?> </td>
</tr>
<?php endforeach; ?>
</table>
I prefer breaking things up a bit more than that. Keeping things separate makes it easier to modify. This should work.
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
echo '<tr>' . "\n";
echo '<td>';
if ($g->rankname != $old_rank) {
$old_rank = $g->rankname;
echo $old_rank;
} else {
echo ' ';
}
echo '</td>';
echo '<td>' . $g->name . '</td>' . "\n";
echo '</tr>' . "\n";
}

Pattern in while loop

<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td>
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
How do I make a pattern for the background color? For ex, grey, blue, grey blue.
There are multiple ways of doing this. Here is one.
<table>
<?php $i = 0; ?>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr<?php echo (++$i & 1 == 1) ? ' class="odd"' : '' ?>>
<td>
<?php echo $row['test'] . " " . ' ($' . $row['test2'] . ") ?><br>
</td>
</tr>
<?php endwhile; ?>
</table>
I suggest giving a CSS class (I've called it "odd" here) to every second row rather than both odd and even. Then you just do:
tr td { background: grey; }
tr.odd td { background: blue; }
in CSS.
You need something like a state variable, where you store wheter the last row was blue or grey. Then you print out the other color and update the state variable for the next pass.
This is one example:
<?php
echo '<table>';
$state = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
if( $state%2 == 0 )
echo '<td style="background-color:grey;">';
else
echo '<td style="background-color:blue;">';
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
echo '</td></tr>';
$state++;
}
echo '</table>';
?>
If it's a 2 colour pattern, use a variable to switch between blue and grey. if more than 2 colours, use a rotating counter
2 colours
$blue = true;
<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td color="<?php echo $blue?'blue':'grey'; $blue ^= true; ?>">
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
More than 2 colours, the general solution:
$colourIndex = 0;
$colours = ('blue', 'red', 'green');
...
...
<td color="<?php echo $colours[$colourIndex]; $colourIndex = ($colourIndex+1)%length($colours); ?>">
You can also use the InfiniteIterator to repeat the sequence again and again. This, like the "rotating counter", works for an arbitrary amount of elements.
$props = new InfiniteIterator(
new ArrayIterator(array('a', 'b', 'c','d', 'e'))
); $props->rewind();
$l = rand(10, 20); // or whatever
for ($i=0; $i<$l; $i++) {
$p = $props->current(); $props->next();
echo 'class="', $p, '"... ';
}

Categories