开发者

sum row and insert into new column

I have a database for keeping track of item weights. the fields are: id, email, order01, order02, order03, order_total

example data:

1  mon@gmail.com        0.250    0.000     0.000    0.000   
2  amy@amy.com          0.510    1.88开发者_开发知识库8     0.219    0.000   
3  ci@mindspring.com    0.219    0.500     0.000    0.000   
4  kim@kim.com          0.219    0.000     0.000    0.000 

I am able to add data (ie new rows or update existing rows) I am also able to use php to display the data in an html table I am also able to sum each row and spit out a single column summed by email. What I need to do is sum each row and insert the sum at the end, in a different column.

example data required:

1  mon@gmail.com       0.250    0.000    0.000    0.250     
2  amy@amy.com         0.510    1.888    0.219    2.617     
3  ci@mindspring.com   0.219    0.500    0.000    0.719     
4  kim@kim.com         0.219    0.000    0.000    0.219     

Again, I am able to display the data in a table, and I'm able to sum each row - I just can't seem to figure out how to get the sum inserted into the proper column

this is the code I am using to sum the data:

$result = mysql_query('SELECT email, (order01+order02+order03) AS order_total FROM `customer_orders`'); 
if (mysql_num_rows($result) > 0) { 
  print '<ul>'; 
  $sum = array(); // initialize 
  while ($myrow = mysql_fetch_array($result)) { 
    $sum[] = $myrow['order_total']; // sum 
    $ordertotal= $myrow['order_total']; 
    print "<li>$ordertotal</li>"; 
  } 
  $sum = array_sum($sum); 
  print "</ul>$sum\n"; 
  } else { 
    print "<h1>No results</h1>\n"; 
  }

That will give me a page with a single column that looks like this:

    0.250
    2.617
    0.719
    0.219

3.8

I don't really care about a total for each column, or a grand total ... just the sum of each row, added to the respective row.


UPDATE mytable SET order_total=order01+order02+order03

would do the trick. However, you should reconsider your table design. If most orders only require 1 item, then you've wasted 2 fields in the database. And you've definitely made it very difficult/impossible for someone to order 4 or more items.

What you should do is split the order details into a sub table, which gives basically infinite flexibility for 1 to 'lots' of orders.


UPDATE your_table SET order_total=(order01 + order01 + order03) WHERE id='id_of_field_to_change'

If you want to do them all at once just take off the where clause.


UPDATE customer_orders
    SET order_total = order01 + order02 + order03
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜