How can I addition mysql numeric data with another mysql numeric data - php

<?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>';
?>

Related

Can't find how to make the php file calculate the average from a received text file that contains more than just numbers

I have a text document that has a set of names and numbers that look like so called grades.txt:
Carolyn:Pittman:93
Audrey:Ford:98
Debra:Prince:82
Jeff:Beldsoe:73
Jovante:Price:99
Pat:Clarke:91
Darla:Floyd:82
Charlene:Character:71
Kanji:Grant:83
Langston:Hughes:95
I am trying to calculate the average of those grades and display the average.
Here is the code:
<html>
<head><title>Grades Results</title></head>
<body>
<?php
// create a variable for scores
$grade = 0;
$average = ($grade+$grade+$grade+$grade+$grade+$grade+$grade+$grade+$grade+$grade)/10;
$highestGrade = 0;
// open grades.txt data file
$gradesFile = fopen("grades.txt", "r");
// read first line
$nextPerson = fgets($gradesFile); // Carolyn:Pittman:93
while(!feof($gradesFile)){
list($firstName, $lastName, $grade) = explode(":", $nextPerson);
print("<p>$firstName</p>");
print("<p>$lastName:</p>");
print("<p>$grade</p>");
$grade = intval($grade);
// determine if ticket price was highest so far
if ($grade > $highestGrade){
$highestGrade = $grade;
// print("<p>Highest grade $highestGrade </p>");
} // end if
// read next line
$nextPerson = fgets($gradesFile);
} // end while
fclose($gradesFile);
// print the highest price
print("<p>The average grade is $average </p>");
print ("<p>Highest grade was $highestGrade </p>");
?>
</body>
</html>
May I have the formula wrong?
You're calculating the average before you read the file. When you assign to $average, $grade contains 0, so you're just averaging 10 values of 0, which is 0.
You need to calculate the total during the loop that reads the file, and at the end of the loop calculate the average by dividing by the count of lines that were read.
$total = 0;
$count = 0;
while($nextPerson = fgets($gradesFile)){
list($firstName, $lastName, $grade) = explode(":", $nextPerson);
print("<p>$firstName</p>");
print("<p>$lastName:</p>");
print("<p>$grade</p>");
$grade = intval($grade);
// determine if ticket price was highest so far
if ($grade > $highestGrade){
$highestGrade = $grade;
// print("<p>Highest grade $highestGrade </p>");
} // end if
$total += $grade;
$count++;
} // end while
if ($count > 0) {
$average = $total / $count;
} else {
$average = 0;
}

Add Numbers Together From Mysql Database in PHP

I need to add some numbers together that are being pulled from a MySQL table to get a total value.
Currently the issue I have is the numbers being added to the end of a string instead.
e.g:
1,2,3,4 becomes 1234 instead of 10
Here is what I am using to get the numbers from the database:
$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
while($row = mysqli_fetch_assoc($count)) {
$total .= $row['Quantity'];
//I Have also tried
$total .= (int)$row['Quantity'];
}
echo $total;
The Quantity Column is set to be an INT in the table so I would have expected it to add together automatically. What am I doing wrong?
You should probably look at the difference between .= and +=
By adding a . in front of = you concatenate - You add the value ad the end of the variable.
If you would use a + in front of your = you would actually get the result you want.
$count = mysqli_query($connect, "SELECT QUANTITY FROM Table");
$total = 0;
while($row = mysqli_fetch_assoc($count)) {
$total += $row['Quantity'];
}
echo $total;
http://php.net/manual/en/language.operators.string.php

Php foreach split list into columns (preferably equally)

I have an ordered list which is 19 entries long (but could change and be more or less). I'm listing it on a drop down menu but because of its length the column is dropping below the fold of the page.
I'd like to create a separate column (ul or div) to either divide the list into 2 or 3 equally, or have set list sizes e.g. max 7 per list.
Any ideas? Current code:
<div id="colour" class="dropmenudiv">
<?php
$sql = "select * from rug_colours where id <> 0 and active = 1 order by name";
$rs = $database->query($sql);
$index = 0;
foreach($rs as $v) {
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
}
?>
Try something along the lines of:
<div id="colour" class="dropmenudiv">
<?php
$sql = "select * from rug_colours where id <> 0 and active = 1 order by name";
$rs = $database->query($sql);
$column_height = 7;
echo "<div class='column'>";
foreach($rs as $idx => $v) {
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
if($idx % $column_height) echo "</div><div class='column'>";
}
echo "</div>";
?>
and for equal split you might try this:
$max_column_height = 7;
$no_of_cols = ceil(count($rs) / $max_column_height);
$column_height = floor($count($rs) / $no_of_cols);
You should use index variable to divide it into 2 or 3 div.
Following is example to make it in three parts:
$index = 0;
foreach($rs as $v) {
if($index > 7){
$index = 0; // reset to zero. You can also seperate it by any tag div or ul if you want
}
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
$index++;
}
For an evenly spread distribution, first divide the number of elements by 7 (or whichever maximum rows you want to allow), rounding upwards. This gives the number of columns. Then divide the number of elements by the number of columns, rounding upwards: this gives you the actual number of rows you need.
I like array_chunk for this purpose:
$maxRowCount = 7;
$colCount = ceil(count($rs) / $maxRowCount);
$chunkSize = ceil(count($rs) / $colCount);
foreach(array_chunk($rs, $chunkSize) as $column) {
echo "<div class='column'>\n";
foreach($column as $v) {
echo "<a href=\"//$base_url/?action=search&colour={$v['id']}\" >{$v['name']}</a>";
}
echo "</div>\n";
}
You can create array of columns based on current index in foreach() loop like
$abc = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
$cols = [];
$perCol = 7;
foreach($abc as $index => $val) {
$colInd = $index / $perCol;
$cols[$colInd][] = $val;
}
print_r($cols);
This will split data in $abc into 3 coluns by 7 items per column.

Sum up dynamically generated fields

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;

Adding up total of mysql_num_rows in a while loop

For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I total all the results inside that while loop? (Total of 133) Thanks.
EDIT:
How about if I want to get the percentage per each result of mysql_num_rows inside my while loop? Example: 4,8,15,16,23,42. Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on..
Try something like this:
$Sum = 0;
while ($SomeInvariant)
{
mysql_query($SomeQuery);
$Sum += mysql_num_rows();
}
echo 'The sum is: ' . $Sum;
However, this approach is not very efficient (what if $SomeInvariant is true for many iterations, and your app has even more concurrent users?). To account for this, I would recommend restructuring your approach so the addition is done in SQL. This way, your query could look something like this: SELECT SUM(ColumnName) FROM ....
UPDATE: Addressing follow-up question in the comments
If you don't already have the sum available from the query, then you'll have to loop over the dataset twice. On the first pass, you'll calculate the sum. On the second pass, you'll calculate the ratio of each value to the sum.
For example:
$Sum = 0;
$Rows = array();
while ($SomeInvariant)
{
mysql_query($SomeQuery);
$Value = mysql_num_rows();
$Rows[] = $Value; // Push the value onto the row array
$Sum += $Value; // Add the value to the cumulative sum
}
echo 'The sum is: ' . $Sum;
foreach ($Rows as $Row)
{
echo $Row . '/' . $Sum . ' = ' . number_format($Row / $Sum) . '%';
}

Categories