I'm trying to run a query like below:
SELECT (SUM(amount) - SUM(refundAmount)) as amount FROM orders WHERE $invoiceFilter AND $websiteFilter
It's getting the sum of the amount column correctly, but it's not subtracting out the refund amount.
What is the correct syntax for a query like this?
try this:
SELECT SUM(amount - refundAmount) AS `amount`
FROM orders
WHERE
invoice = $invoiceFilter
AND website = $websiteFilter;
You can use subqueries in the FROM clause.
SQL:
SELECT amount - refund
FROM (SELECT SUM(amount) as amount
FROM orders
WHERE invoice = 'invoiceFilter' AND website = 'websiteFilter') as a,
(SELECT SUM(refundAmount) as refund
FROM orders
WHERE invoice = 'invoiceFilter' AND website = 'websiteFilter') as b;
PHP:
mysql_query("SELECT amount - refund
FROM (SELECT SUM(amount) as amount
FROM orders
WHERE invoice = '" . mysql_real_escape_string($invoiceFilter). "'
AND website = '" . mysql_real_escape_string($websiteFilter). "') as a,
(SELECT SUM(refundAmount) as refund
FROM orders
WHERE invoice = '" . mysql_real_escape_string($invoiceFilter). "'
AND website = '" . mysql_real_escape_string($websiteFilter). "') as b; ");
You maybe missing something like a reference column to filter the data you need to process. Something like:
SELECT (SUM(amount) - SUM(refundAmount)) AS amount
FROM orders
WHERE
<a_column> = $invoiceFilter
AND <another_column> = $websiteFilter;
Related
I am trying to get the Total Sum of values from a table. Query works without WHERE Clause, but i need to get the total sum per user. Like user ABC has 100USD and user BDC has 200USD. Here is the code
$PWithdrawls = mysqli_query($con, "SELECT * FROM withdraw WHERE status='Pending'");
$S_NO = 0;
while ($row = mysqli_fetch_assoc($PWithdrawls)) {
$S_NO++;
$posted_by = mysqli_query($con,"SELECT * FROM users WHERE userId=".$row['seller_id']);
$user_ad = mysqli_fetch_assoc($posted_by);
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id']);
$sum_amount = mysqli_fetch_assoc($TotalOrders_Amount);
$sum = $sum_amount['total'];
And here is my call
<td>$<?php echo $sum; ?></td>
Here is DB
Think you have error in your SQL Query:
SELECT SUM(amount) as total FROM orders WHERE userId=".$row['seller_id'] GROUP BY userId LIMIT 1
You need to use GROUP BY to get actual SUM. Also you can get all users with Total, there is no need to second query:
SELECT u.*, SUM(o.amount) AS total
FROM users u
LEFT JOIN orders o ON (o.userId = u.id)
GROUP BY u.userId
This should get you entire user row + total of their orders.
I found the issue. I was calling the wrong variable. userId was not in my table, it was seller_id. So correct query was
$TotalOrders_Amount = mysqli_query($con, "SELECT SUM(amount) as total FROM orders WHERE seller_id=".$row['seller_id']);
Thanks to everyone. I really appreciate.
I want to create an order for a customer in the administration. The customer has certain credit (let's say $200). The order total is calculated like order total - customer's credit = new order total.
The problem is the customer's credit does not change after creating an order.
For example:
the order total is: $500
credit is: $200
then the order total is : $500 - $200 = $300
but the customer's credit is still: $200
Has anybody else had the same problem?
I try to change the status of that order, both processing and setting, but it doesn't work.
The transaction in customer info page does not change.
I have checked the code in backend - there is no code that would operate with oc_customer_transaction table.
In frontend, there is a function in /catalog/model/total/credit.php
public function confirm($order_info, $order_total) {
$this->language->load('total/credit');
if ($order_info['customer_id']) {
$this->db->query("INSERT INTO " . DB_PREFIX . "customer_transaction SET
customer_id = '" . (int)$order_info['customer_id'] . "',
order_id = '" . (int)$order_info['order_id'] . "',
description = '" . $this->db->escape(
sprintf($this->language->get('text_order_id'),
(int)$order_info['order_id'])) . "',
amount = '" . (float)$order_total['value'] . "',
date_added = NOW()");
}
}
it is called during the checkout process to recalculate customer's credit balance. But I haven't found such code in backend.
I already fix that.
code:
$this->db->query("INSERT INTO " . DB_PREFIX . "customer_transaction SET
customer_id = '" . (int)$order_info['customer_id'] . "',
order_id = '" . (int)$order_info['order_id'] . "',
description = '" . $this->db->escape(
sprintf($this->language->get('text_order_id'),
(int)$order_info['order_id'])) . "',
amount = '" . (float)$order_total['value'] . "',
date_added = NOW()");
just add the credit calculate code when at following place:
1./admin/model/sale/order.php addOrder method
a. when you add product to a new customer order in the backend, the system will send request to the frontend (/catalog/checkout/mannual.php index ) wo calculate the order total(such as: subtotal, credit, shipping, total). after this request, order total in the page will be refreshed
b. when you save the order, the (admin/model/sale/order.php) addOrder method will be called eventually. You just need add code above to that function.
insert into..... customer_transaction means use the credit
2./admin/model/sale/order.php editOrder method
a. when you edit a order, the each item in totals will be changed. so, you should delete all credit you used for this order before.
delete * from oc_customer_transaction where 'order_id'=$order_id
b. since the each item of totals(involve credit) has been recalculated in step1, so this method will receive the new credit amount. just insert the new amount by code blow
3.you do not need to change admin/model/sale/order.php deleteOrder method
because it delete all totals, include item in the data table oc_customer_transaction
things done!
I'm trying to select all of the products that a user has purchased from my site, based on an order ID.
$orderid = mysql_query("SELECT MAX(orders_id) FROM orders") or die(mysql_error());
$orderid = mysql_fetch_row($orderid);
$productinfo = mysql_query("SELECT products_model, products_name, products_price, products_quantity FROM orders_products WHERE orders_id=" . $orderid[0]);
$productinfo = mysql_fetch_row($productinfo);
echo $productinfo[0] . " | " . $productinfo[1] . " | $" . $productinfo[2] . " | " . $productinfo[3] . "<br><br>";
This will pull one product from the database, but if the customer ordered 8 items, I would need this to loop until all of the products with an order ID of $orderid[0] have been selected. What would be the best way to go about this? Any help is appreciated!
A few things.
First, everyone here will tell you to look into using mysqli or pdo as an alternative to mysql_query, as they are much more secure, and actually easier to maintain and use.
See this article:
http://www.pontikis.net/blog/how-to-use-php-improved-mysqli-extension-and-why-you-should
Second, you could easily cut down your code by writing more efficient queries.
In this case you would want to use a SQL JOIN. (more about joins here http://www.sitepoint.com/understanding-sql-joins-mysql-database/)
SELECT products_model, products_name, products_price, products_quantity
FROM orders_products as products
JOIN orders as orders on products.order_id = order.order_id
WHERE products.order_id = {whatever order id you are trying to find}
This will give you all products that have been ordered for each order id.
And use a while loop to loop through all of your results that come out of your query
any ideas how to get orderTotal and orderId inside the tpl_checkout_success_default for the conversions tracking purposes ?
So far it looks like order id can be accessed by using this variable $zv_orders_id but how to get order total ?
will this code work:
$orders_query = "SELECT * FROM zen_orders WHERE orders_id = " . $zv_orders_id ." LIMIT 1";
$orders = $db->Execute($orders_query);
$order_total = $orders->fields['order_total'];
many thanks,
cheers
look in /includes/modules/pages/checkout_success/header_php.php
in there you will see the queries already being run by zencart to do with your order, and id say its already pulling out the info you want.
so you just need to set said data you need to a variable that you can then use in your tpl_checkout_success_default.php file.
eg, something like $customer_has_gv_balance, you will see where it is set in the hearder file and then used in the template file
heres something i found in order.php that would almost do it as is:
$order_total_query = "select text, value
from " . TABLE_ORDERS_TOTAL . "
where orders_id = '" . (int)$order_id . "'
and class = 'ot_total'";
$order_total = $db->Execute($order_total_query);
For a simple tracking code like one used for a shopping comparison site, I've used the following for the order ID and order amount. Use these in the tpl_checkout_success.php page
Order ID:
echo $zv_orders_id;
Use this select statement:
$to_send_sql = 'select REPLACE (text,"$","") text from orders_total where orders_id = '.$zv_orders_id.' and class = "ot_subtotal"';
$to_send= $db->Execute($to_send_sql);
Order amount:
echo $to_send->fields['text'];
Hope this helps someone!
<?
$tablae = mysql_query("SELECT * FROM order_history where (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "' GROUP BY user_id");
while ($order = mysql_fetch_array($tablae)) {
?>
<tr>
<?
$tablaes = mysql_query("SELECT * FROM members where id='$order[user_id]'");
$user = mysql_fetch_array($tablaes);
$idsd=$user['id'];
$rPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
$hdPaid = mysql_fetch_array($rPaid);
$sPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE user_id='$idsd' AND (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
while ($hPaid = mysql_fetch_array($sPaid)) {
?>
<td><?=$user['username']?></td>
<td><?=$hPaid['total']?></td>
<?
}
?>
</tr>
<? } ?>
This gets me this result http://dl.dropbox.com/u/14384295/test.jpeg
I want to order the price totals by DESC.
I would need
$sPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE user_id='$idsd' AND (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
the total on that to be ordered by DESC.
Be really carefull with GROUP BY instructions in your SQL query. All columns which are in the result and which are not aggregate expressions (expressions would be the count, SUM, max, etc working on the group and not on the rows) should be in your group by expression;
Here you use a select *, you should try to list the real columns instead, and get this list in your group by, or use only SELECT user_id.
Most database would prevent you of running such not-very-well-formted group by query, but MySQl is not bailing you, tthat does not mean he won't gives you completly wrong results if you do not rexpect this rule (all columns which are not aggregates must be in the group by).
Then you should be able to order by an agregate expression by reusing this expression and not his alias in the order clause.
You could either use client side sorting with javascript, there are some nice jQuery addons that can do that.
Or you have to totaly rewrite your code to have a single sql using joins and group by.
But I cannot realy follow the logic with $rPaid, $hPaid and $sPaid so I cannot help you there.