this may sound lame but i am stuck up with summing up the values retrieved from mysql.
i want to sum up the grand total of the sales invoice items that is retrieved from mysql database.
following is the code for sub total for each line which is fine.
while($row = mysql_fetch_array($qry)){
echo $row['b'] * $row['c'];
}
'b' is the quantity and 'c' is the price.all these values are retrieved from mysql and the no of rows is variable and all this is inside the while loop.
Now outside of the while loop, the last row, i want the grand total. can somebody point me in the right direction. i tried
echo SUM($row['b'] * $row['c']);
but this doesn't work and gives an error. i am sure i am doing it wrongly.
$total = 0;
while($row = mysql_fetch_array($qry))
{
echo $row['b'] * $row['c'];
$total += ($row['b'] * $row['c']);
}
// at the end, $total = grand total
Why not use SQL for things SQL does best?
SELECT SUM(b*c)
FROM table
Simple as that.
Related
Can't believe this is giving me a problem but here it is. An example of the query and code is:
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
/* I want to echo broker_id and angent_id only once here,
before the while loop, because the values are all the same */
while ($row = pg_fetch_array($sql_res)){
echo $order_number;
}
Assume broker and agent id numbers are each the same in every row. I don't want to echo them every time in the loop. I just want them to echo one time before the loop. Since they are the same, it does not matter which row they are echoed from.
I figured out a different way for a means to an end. It works well.
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
$count = 0;
while ($row = pg_fetch_array($sql_res)){
if ($count == 0) {
echo $broker_id;
echo $agent_id;
}
echo $order_number;
$count += 1;
}
I realize I'm echoing the broker and agent IDs inside the while loop, but it's only an echo the first time through, and I can display them at top. And then every unique order is echoed. Visually, it accomplished what was needed for the end user.
The issue is not how I am generating the number, that is working fine for a different app I have. The issue is counting the total number of boxes and iterating through a forloop that many times. Right now I am multiplying box_ct * qty_ord to get the total boxes. BTW, I am still trying to understand everything I can do with foreach and for loops, so if anyone has a better idea, Great.
CLARIFICATION: I am searching the database by order number and pulling back qty_ord, box_ct, and item_no for each. On some orders there is more than one item. So for each item I need to multiply qty_ord by box_ct = count and for that specific item I need to iterate through the loop based on what my count is.Right now if I remove the foreach and hardcode the for loop count variable it works fine. Any ideas on what is wrong with my foreach?
qty_ord | box_ct | item_no
------------------------
1 2 10001
3 3 10002
2 1 10003
2 3 10004
2 6 10005
Below is my code.
$sql ="SELECT imitmidx_sql.box_ct, oeordlin_sql.item_no, oeordlin_sql.qty_ord
FROM imitmidx_sql
JOIN oeordlin_sql ON oeordlin_sql.item_no = imitmidx_sql.item_no WHERE ord_no ='$orderNum'";
$query = odbc_exec($conn, $sql);
$row7 = odbc_fetch_array($query);
foreach($row7['item_no'] as $item){
$count = $row7['qty_ord'] * $row7['box_ct'];
for($counter = 0; $counter <= $count; $counter++){
//GRAB NUMBER FROM FILE
$sscc = file_get_contents("ucc128.txt");
//INCREMENT NUMBER
$sscc++;
//PUT THE NUMBER BACK IN FILE
$sscc = file_put_contents("ucc128.txt", $sscc);
//COMBINE STATIC NUMBER AND NUMBER FROM FILE
$ssccnumber = "00950000".$sscc;
//CREATE CHECK DIGIT MATH
$ssccnumArray = str_split((string)$ssccnumber);
$ssccstep1 = array_combine(range(1, count($ssccnumArray)), $ssccnumArray);
$ssccstep2 = 0;
$ssccstep4 = 0;
foreach($ssccnumArray as $k => $v){
if($k%2){
$ssccstep2 += (int)$v;
}else{
$ssccstep4 += (int)$v;
}
}
$ssccstep3 = (int)$ssccstep2 * 3;
$ssccstep5 = (int)$ssccstep3 + (int)$step4;
$ssccCheckDigit = (ceil($ssccstep5 / 10) * 10) - $ssccstep5;
//END CREATE CHECK DIGIT
//CONCATENATE FULL NUMBER
$sscc1 = $ssccnumber.$ssccCheckDigit;
$sql = "INSERT INTO ucc128 (sscc, ord_no) VALUES ('$sscc1' ,'$orderNum')";
#echo $sql.'<br />';
odbc_exec($connPRONUMBER, $sql);
}
}
I believe your issue may be with the following:
foreach($row7['item_no'] as $item){
$count = $row7['qty_ord'] * $row7['box_ct'];
//...
}
This should be:
foreach($row7['item_no'] as $item){
$count = $item['qty_ord'] * $item['box_ct'];
//...
}
You are grabbing data from the query results, as opposed to the current row.
My foreach was not working, so what I did instead was get the sum using my SQL query.
SELECT SUM(imitmidx_sql.box_ct * oeordlin_sql.qty_ord) AS total
FROM imitmidx_sql
JOIN oeordlin_sql ON oeordlin_sql.item_no = imitmidx_sql.item_no WHERE ord_no ='$orderNum'
I was then able to ouput it and save $row7['total'] to the variable $count.
I have a table like this: id | item_name | price
I have a loop that displays all items with the grand total at the bottom.
$total_price = 0;
foreach($items as $item)
{
echo $item->item_name;
echo $item->price;
$total_price += $item->price;
}
echo $total_price;
However, what I need is to display the $total_price at the TOP of the page, before I loop through all the items.
Is it better to loop through the foreach again at the top of the page to calculate the total price, or should I be making a separate database call that only returns the total price?
It's simple and fast decision
$total_price = 0;
$print = '';
foreach($items as $item)
{
$print .= $item->item_name;
$print .= $item->price;
$total_price += $item->price;
}
echo $total_price;
echo $print;
If you can get sum from SQL base it will be more best solution. In MySQL use function SUM()
Example:
SELECT SUM(price) AS total FROM ...
This is one of the reasons why you should never mix php code and direct output. I would suggest you look into one of the template engines for php.
Unless you are writing php-cli do all the operations before you start to output. This will increase the flexibility of your code a lot.
Smarty is one of my favourite tempelate engines, easy to setup and with powerfull features, but that's my opinion.
Maybe you need use MySQL query like this:
SELECT SUM(price) FROM your_table
I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)
MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".
You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.
What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.
You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).
I have a loop in PHP as follows:
$getDetails = mssql_query ("SELECT * FROM BasketItems
WHERE BasketID = '".$_GET['id']."' ");
while ($detailsrow = mssql_fetch_array($getDetails)) {
$TotalSetPrice = $detailsrow['FinalPrice'] * $detailsrow['Qty'];
echo $TotalSetPrice;
$numberofent = count($detailsrow['FinalPrice']);
echo "######NUMBER#####: $numberofent";
$TotalPrice = ?????;
######VARIOUS DATA##############
}
So ok i'm not an expert at PHP by any means, thats the first thing. FinalPrice is the price of an item in the DB that someone has selected. However the customer can have any number of quantity of those items.
So FinalPrice * Qty = TotalSetPrice
However the customer may also have different sets of items within the basket.
So I need to calculate TotalSetPrice * (Number of sets of items Within the DB)
SO I googled, and came up with count(), but if I just count($detailsrow) it returns 56 entries, this is the number of overall pieces of data if that makes sense. I just want to count the dumber of actual data sets. I tried counting finalprice but that just returns 1, which isn't correct either.
Can anyone give me some guidence on how you are meant to count the number of entries in an array loop such as this. I hope that makes more sense than I feel it does.
SELECT FinalPrice, Qty,(FinalPrice * Qty) AS TotalSetPrice
Just use mysql, so that you no longer use with php which you will need to write a longer code
$TotalPrice += $TotalSetPrice;
This is short for: $TotalPrice = $TotalPrice + $TotalSetPrice;