I have created a script that populates fields of a table dynamically using php. If you look at the snippet of code below, I have hit a brick wall now that I want to add all $sub_total to create a $total_cost. Not sure if I am explaining this well but any direction would be much appreciated.
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// Calculate hours done per day
$hrs_done = $row['time_out'] - $row['time_in'];
if($hrs_done > $row['con_hr']){$hrs = $hrs_done;}
else{$hrs = $hrs_done;}
// echo out results into a table
echo "<tr>";
echo '<td bgcolor="#FFFFFF">' . $row['date'] . '</td>';
echo '<td bgcolor="#FFFFFF">' . $hrs . '</td>';
echo '<td bgcolor="#FFFFFF">' . $row['rate'] . '</td>';
echo '<td bgcolor="#FFFFFF">'?>
// Multiply hrs by rate to get sub total charge for day
<?php $sub_total = $hrs * $row['rate'];
echo $sub_total ;
?>
<?php '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
First, you should look for tutorials that use mysqli or PDO for database access, as mysql_* functions are deprecated.
Second this problem is as easy as just adding up the subtotal items as you iterate through the loop
$grand_total = 0;
while($row = mysql_fetch_array( $result )) {
// your other code omitted for clarity
$sub_total = $hrs * $row['rate'];
$grand_total += $sub_total;
echo $sub_total ;
// more code
}
echo $grand_total;
If I understand your desired behaviour correctly.
During the loop add each $sub_total to $total_cost and echo this after you've completed the while loop
<?php
$total_cost = 0;
while($row = mysql_fetch_array( $result )) {
$sub_total = $hrs * $row['rate'];
$total_cost += $sub_total;
}
echo "Total cost: " . $total_cost;
?>
Your IF/ELSE block leads to one and the same result in both conditions. Is that the desired result?
On the other hand, I'm not sure, if I understood you correct, but if I did, here's my answer.
Since you want to recieve all the $sub_total, you need all the other vars which have built $sub_total:
They are:
$hrs = $hrs_done = $row['time_out'] - $row['time_in']
$row['rate'];
If you try with the SUM() MySQL function, you will recieve the sum of the mentioned columns:
SELECT sum(time_out) as 'sum_time_out', sum(time_in) as 'sum_time_in', sum(rate) as 'sum_rate' FROM myTable;
$hrs_sum = $hrs_done_sum = $row['sum_time_out'] - $row['sum_time_in'];
$stotal_cost = $hrs)sum * $row['sum_rate'];
Each iteration of the while loop creates a new variable $subtotal that you want to add to your constant variable $total.
so within the loop you can add $subtotal to $total and echo the $total after the while loop exits
while($row = mysql_fetch_array( $result ))
{
// your code
$total = $total + $subtotal; // shorthand is - $total += $subtotal.
}
echo $total;
Related
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>";
?>
<?php
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo "<h2> total cost of this month is $".$sum. "</h2>";
?>
but the result say
<br>
Notice: Undefined variable: sum in
C:\xampp\htdocs\work_shop\back_end\data_input_output\result.php on
line 57
<br>
total cost of this month is $300
which is correct result....
<br>
How can I solve this problem...??
You need to define $sum variable outside loop. Try this-
<?php
$sum = 0; // define sum outside loop
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo "<h2> total cost of this month is $".$sum. "</h2>";
?>
$sum is undefined because you are only adding, and not setting a value.
<?php
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
$sum = 0;
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo '<h2> total cost of this month is $'.$sum.'</h2>';
?>
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 am completely new in PHP so this question might be stupid. I could not find an answer after searching for hours.
I have made a query with a foreach loop but it does not show it right in the table I create. The part from the foreach show all in the field next to the last country.
I have tried to put the on all kind of other places but the result stays the same it does not come in the right column.
$query = "SELECT COUNT(landofbirth) as c, landofbirth FROM dog WHERE landofbirth IS NOT NULL GROUP BY landofbirth ORDER BY c desc LIMIT 1000";
$result = mysql_query($query) ;
$values = array();
$pct = array();
$total = 0;
while ($line = mysql_fetch_array($result)) {
echo "<tr><td>";
$values[$line[1]] = $line[0];
$total += $line[0];
echo "$line[1]</td><td> ";
echo "$line[0] </td><td>"; }
foreach($values as $key => $value) {
$pct[$key] = $value/$total ;
$count2 = $pct[$key] * 100;
$count = number_format($count2, 2);
echo "$count %"; }
echo "</td></tr>";
Your code is a bit garbled, perhaps from moving it around one too many times.
I always find it helpful to separate the display items one-by-one, even put them each on individual lines and away from the "calculation" code for better visuals when editing the code.
I'm not exactly sure if this is what you're looking for, but I think this display will be close (and/or easily modifiable):
while ($line = mysql_fetch_array($result)) {
$values[$line[1]] = $line[0];
$total += $line[0];
}
foreach($values as $key => $value) {
$pct[$key] = $value/$total ;
$count2 = $pct[$key] * 100;
$count = number_format($count2, 2);
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '<td>' . $count . '%</td>';
echo '</tr>';
}
Side Note (not answer specific)
It is recommended that you do not develop with the deprecated mysql extension in PHP. Instead, you should use the alternative and maintained mysqli or PDO extensions. Both are far more secure to use and provide beneficial features such as prepared statements!
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
<p>$i. <?php echo $row['comment'] ?></p>
<div class="border"></div>
$i++;
}
How could I do to not output <div class="border"></div> under the last comment?
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$number = mysql_num_rows($sql);
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
echo '<p>' . $i . $row['comment'] . '</p>';
if ($i < $number)
{
echo '<div class="border"></div>';
}
$i ++;
}
Using WebDevHobo's suggestion.
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$output = array ();
while ($row = mysql_fetch_assoc($sql)) {
$output[] = $row['comment'];
}
echo join('<div class="border"></div>', $output);
$number = mysql_num_rows($sql);
This will tell you how many rows will be returned. Based on that, you can make sure that the last on does not have the DIV.
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
$out_data[] = "<p>$i {$row['comment']} </p>";
$i++;
}
$divider = '<div class="border"></div>';
$output = implode ($divider, $out_data);
echo $output;
$rslt = mysql_query("SELECT * FROM comments WHERE user = 1");
$i = 1;
if ($row = mysql_fetch_assoc($rslt)) {
echo '<p>'. $i . ' '. $row['comment'] . '</p>';
$i++;
while ($row = mysql_fetch_assoc($rslt)){
echo '<div class="border"></div>';
echo '<p>'. $i . ' ' . $row['comment'] . '</p>';
$i++;
} // end while
} // end if
Avoids needing to know the number of rows.
Executes the if statement only once instead of each loop.
The HTML and php were kind of messy and inconsistent, so I just assumed the whole block was within php tags. Obviously, open and close the php tag as you see fit.
This is largely a style issue, but I decided that the variable name $sql was a bit misleading, as it is often and commonly used to hold the string of the sql statement to be executed, I therefore changed the variable name to $rslt.
A general answer to this type of problem, and using Javascript because it's easy to throw in a console and play with:
var count = 0;
var foo = 3;
while( count < 3 ) {
console.log("Header - " + count);
console.log("Body - "+ count);
console.log("Footer - " + count);
count++;
}
This will print:
Header - 0
Body - 0
Footer - 0
Header - 1
Body - 1
Footer - 1
Header - 2
Body - 2
Footer - 2
The case being requested is basically saying "Print a footer on all but the last element."
If you consider the second loop iteration as simply a continuation of the first you can see how to do this without needing to find the total number of records - e.g. no need to do a second query for count. More succinctly: when you're stuck trying to figure out how to do something using a loop (or recursion) you should try actually writing out what your loop does, but without actually looping - e.g. copy and paste the loop block at least three times.
Rather than do that here, I'm just going to finish with the answer, and leave the derivation to the reader :~)
var count = 0;
var foo = 3;
while( count < 3 ) {
if( count > 0 ) {
console.log("Footer - " + (count - 1));
}
console.log("Header - " + count);
console.log("Body - "+ count);
count++;
}