Keep the remaining value after subtract in php while loop - php

I want to update three invoice data that belongs to a customer like below:
function updateInvoice($dbh, $id, $amount, $bal, $payer){
$q = $dbh->query("SELECT * FROM `zinvoice` WHERE `id`='$id'
AND `status` IN ('Balance','Not Paid')");
$nrow = count($q->fetchAll());
$remain = 0;
if($nrow==1){
//update the amount
if($amount>$bal){
$remain = $amount-$bal;
$dbh->query("UPDATE zinvoice SET paidamount=(paidamount+$bal),
balanceamount='0', status='Paid'
WHERE id='$id'");
//payment history update
}else if($amount==$bal){
$remain = 0;
$dbh->query("UPDATE zinvoice SET paidamount=(paidamount+$bal),
balanceamount='0', status='Paid'
WHERE id='$id'");
//payment history update
}else{
$newbal = $bal-$amount;
$dbh->query("UPDATE zinvoice SET paidamount=(paidamount+$amount),
balanceamount='$newbal', status='Balance'
WHERE id='$id'");
$remain = 0;
//payment history update
}
}else{
//Nothing to update Because there is no Invoice with balance or not paid
}
return $remain;
}
Now I want to update multiple invoices by a customer id=2. Customer with id=2 has three invoices with total amount of 1500, invoice id=1 has amount=500, invoice id=2 has amount=700, invoice id=3 has amount=300
//Loop to update
$q = $dbh->query("SELECT * FROM zinvoice WHERE customerid='$cid'");
while($row =$q->fetch(PDO::FETCH_OBJ)):
$remain = updateInvoice($dbh, $row->id, $amount, $row->balanceamount, $payer);
if($remain>=1){
updateInvoice($dbh, $row->id, $remain, $row->balanceamount, $payer);
}else{
//nothing
}
endwhile;
$amount would come from a form//amount = 800
$cid would also come from a form//cid = 2
$payer would also come from a form//payer = john
The problem is that this code updated all the invoices to status=Paid. I want this code to update Invoice id=2 which has balance amount=700 and as there would be 100 amount remaining, it will continue to update the other invoices, say Invoice id=3. But Invoice id=3 has a balance amount=300, which is more than 100 amount, it will subtract 100from it and Invoice id=3 would have 200 balance amount. And there are no more amount left and would stop updating.
How would I achieve my desired output?
Note: I am not using prepared statement to avoid more codes here. And this code would be vulnerable to sql injection.

Related

how to get sum on every loop on the table

I have a problem on breaking down the amount of the given payment, I think i was missing something on my code. This is my table below.
If i have payment of 5,000, it will deduct on the first row and the remaining sum will send to the 2nd row.
//this is the payment
$payment = 5000;
$temp = '';
//the loop of function
$data = payment_breakdown();
foreach ($data as $row) {
$amount = $row['AMOUNT'] - $payment."\n";
}
//handle the difference of every loop of the function
$temp = $amount;
//result of the amount
echo $amount;
//this is my function to get the data from the table
function payment_breakdown(){
$db = database2();
$query = "SELECT AMOUNT FROM TABLE1";
$cmd = $db->prepare($query);
$cmd->execute();
$rows = $cmd->fetchAll();
$db = null;
return $rows;
}
supposedly if the amount on the table is this
Data From Table | The Payment
3000 | 3000
3000 | 2000
You could do it in SQL:
SELECT
amount,
paid,
sum(amount-paid) open
FROM
payment
GROUP BY amount, paid
WITH ROLLUP
HAVING
amount IS NULL
OR paid IS NOT NULL
;
Based on the data
INSERT INTO payment (amount, paid)
VALUES
(3000,3000),
(3000,2000),
(4000,1000)
;
you get
amount;paid; open
3000 ;2000; 1000
3000 ;3000; 0
4000 ;1000; 3000
NULL ;NULL; 4000
Or you might want a simple substraction from a deposit:
SET #credit := 5000;
SELECT
amount,
#credit := #credit-amount credit
FROM payment
;
SELECT #credit;
However, in the latter case you should rather store all payments and amounts to pay into database tables and sum up all together. Consider refactoring your database structure design.

Hi what i am doing wrong with this query?

I want to select the income amount from income table, update the total income and subtract the income from the total income. Then delete the row.
public function delete($id)
{
$this->db->get('income');
$this->db->select('income_amount');
$this->db->query('update total_income set amount=amount-'.$this->db->select('income_amount'));
$this->db->where('income_id', $id);
$this->db->delete('income');
}
Unless I have misunderstood your question, you want to do the following :
Select income_amount from the income table :
$this->db->select('income_amount');
$query = $this->db->get('income');
$row = $query->row();
if (isset($row)) {
$income_amount = $row->income_amount;
}
Update the total_income table by substracting $income_amount from all the amount values of the table :
$this->db->set('amount', 'amount-'.$income_amount);
$this->db->update('total_income');
Delete the row identified by $id from the income table :
$this->db->delete('income', array('income_id' => $id));

Need help on some logic to perform mysql insert query?

I'm developing a shopping cart using php, now I stuck at some point as follow.
There are tables like: customers, products, orders, order_detail
products table:
id | name | quantity
order_detail table:
order_id | product_id | quantity
I completely done for add product to cart and customer can submit the order to database, admin can remove or delete orders from backend and customers can remove orders list or delete orders from frontend if that ordered still not confirm payment.
Example:
"customer1" order 10 products, order ID is #907987899 and "product1" customer1 order quantity = 2, "product2" customer1 order quantity = 5 and so on.....
if the ordered still not confirm then customer still can remove product from the ordered list, and also can delete the entire ordered.
My problem now is: if Customers or Admin cancel or delete the ordered that still not confirm payment then I want to return product quantity from order_detail table list back to products table. by the time when customer submitted the order then product quantity is subtract from product table.
Here is my code that return quantity back to products:
require '../../init.php';
require $ROOT . '/functions/basic.php';
if(isset($_POST['id']))
{
$id = htmlspecialchars($_POST['id']);
$delete = dbQuery("DELETE FROM orders WHERE order_id = '$id'");
if($delete == true)
{
//unlink($ROOT . '/upload/products/' . $image);
$select_product = dbAll("SELECT product_id, quantity FROM order_detail WHERE order_id = '$id'");
foreach($select_product as $product)
{
$quantity = $product['quantity'];
$product_id = $product['product_id'];
$return_product_quantity = dbQuery("UPDATE products SET quantity = (quantity + $quantity) WHERE product_id = $product_id");
}
if($return_product_quantity == true)
{
$delete_order_detail = dbQuery("DELETE FROM order_detail WHERE order_id = '$id'");
if($delete_order_detail == true)
{
echo "OK";
}
else
{
echo "Can't delete order detail information";
}
}
}
else
{
echo "Can't delete order row";
}
}
but the query it seem not work as my required, so please help me how to handle this kind of logic to perform my required.
Thanks in advance.
You are trying to use the variable quantity in your UPDATE even though it has no value. Try this instead:
$return_product_quantity = dbQuery("UPDATE products
SET quantity = ((SELECT quantity FROM products WHERE product_id = $product_id) + $quantity)
WHERE product_id = $product_id");

how to update a table and insert a new record to another table in one query?

I have two table in mysql that is product and sell. The product contain the stock and the sell contain the purchasing record. Now i want to sell a product from the stock when i insert the quantity of selling item into the sell table then the same amount should be decrease in the stock that is product table. Please help me for the query.
Sell table insertion.
$cus_id = $_POST['customer'];
$reg_id = $_POST['cus_region'];
$cat_id = $_POST['product'];
$name = $_POST['name'];
$price = $_POST['unit_price'];
$quantity = $_POST['quantity'];
$date = $_POST['datepicker'];
$total = $price * $quantity;
$payment = $_POST['payment'];
$remainig = $total - $payment;
$query = "INSERT INTO sell SET cus_id = '".$cus_id."',reg_id = '".$reg_id."', cat_id = '".$cat_id."',product = '".$name."',selling_price = '".$price."',selling_date = '".$date."',item_quantity = '".$quantity."',amount_paid= '".$payment."',total_price = '".$total."', remaining = '".$remainig."'";
$res = mysql_query($query);
Two way to resolve that,
1) if you are getting the quantity of product you can make second query to deduct the quantity from stack table (product table)
2) You can use trigger for such operations, while you insert in to sales table that same quantity you can reduce from the product table
You have to just change or decrease the quantity of the product in PRODUCT table. So, you have to use UPDATE query.
This can solve your issue:
1) I consider that your cat_id is the unique product key to identify a product in your PRODUCT table.
2) I consider that you have quantity column in PRODUCT table, which store the quatity of the product. And 1 product is being sold at a time.
UPDATE TABLE_NAME SET quantity=quantity - 1
WHERE cat_id = "SOME_INT_ID_WITHOUT_QUOTES"

PHP mySQL result array - while a row's id remains the same do something, when the row's id changes move on

I have a query which is searching a database for orders. My SQL query returns order information with the order id being the key (the id is repeating for orders with more than one product) and order information attached to that including product qty and variation.
The query joins a few tables and outputs as follows
|--orderid--|--orderstatus--|--ordcustid--|--orderprodname--|--orderprodqty--|--orderqty--|
|---12635---|-----11--------|-----4192----|----Product1-----|--------1-------|-----2------|
|---12635---|-----11--------|-----4192----|----Product2-----|--------1-------|-----2------|
|---12636---|-----11--------|-----3531----|----Product3-----|--------1-------|-----1------|
As you can see above. Customer 4192 has made 1 order (orderid 12635) that has 2 products. Customer 3531 has made 1 order that has 1 product (orderid 12636).
I'm wanting to capture the information for each order and put it together. So while the order id is the same I'm collecting the information.
My current script looks like this, but it just works on every row.
$result = mysql_query("
SELECT *
FROM orders, orderproducts, productimage, customers
WHERE orders.orderid = orderproducts.orderorderid
AND orderproducts.orderprodid = productimage.imageprodid
AND orders.ordcustid = customers.customerid
AND ordstatus = '11'
ORDER BY orderid
");
while($row = mysql_fetch_array($result))
{
//do stuff
}
The purpose of the script is to mail the information for each order. What my current script is doing is mailing the customer for every product (i.e. customer 4192 would get two separate emails - 1 for Product1 and 1 for Product2). What I'm wanting to do is email customer 4192 with both products on the same email.
How can I improve my script so that while the orderid is the same it will get information from all of the rows where the orderid is the same (eg orderproductname, qty ) and then continue when the order id changes.
Try adding this bit of code before your loop:
$last_id = 0;
And in your while() loop:
if ( $last_id != $row['orderid'] ) {
// New Order - do some initiation stuff
$last_id = $row['orderid'];
} else {
// Continuing the current order - do some different stuff
}
Here's the code altogether:
$result = mysql_query("
SELECT *
FROM orders, orderproducts, productimage, customers
WHERE orders.orderid = orderproducts.orderorderid
AND orderproducts.orderprodid = productimage.imageprodid
AND orders.ordcustid = customers.customerid
AND ordstatus = '11'
ORDER BY orderid
");
$last_id = 0;
while($row = mysql_fetch_array($result)) {
if ( $last_id != $row['orderid'] ){
// Initiate a new order
$message_body = ''; // Reset message body for each order
$last_id = $row['orderid']; // Keep track of the orderid last used
if ( $last_id > 0 ){
// Make certain we didn't just begin the loop, then email the customer
echo "SAMPLE MESSAGE BODY FOR ORDER $last_id <br/>\r\n";
echo $message_body;
// Uncomment following lines to send an email
// $headers = $headers = 'From: My Store <info#mystore.com>\r\nContent-Type: text/html; charset=ISO-8859-1\r\n";
// $success = mail( 'customer#email.com', 'Order Confirmation', $message_body, $headers);
}
} else {
// Step through current order
// Add a line to the message body for each product record
$message_body .= "Product {$row['orderprodname']}, Qty: {$row['orderprodqty']} <br/>\r\n";
}
}
Keep track of which orderID you're on, and build up an email until the orderID changes. When it does, you send the email, and start a new one for the new order. e.g.
$cur_order = null;
$order_data = array();
while($row = mysql_fetch_assoc($result)) {
if ($cur_order !== $row['orderid']) {
sendOrderEmail($order_data);
$cur_order = $row['orderid'];
$order_data = array();
}
$order_data[] = $row;
}
I think the best option would be is to use group_concat of product names in the query itself. For example ,
SELECT *,group_concat(orderprodname)
FROM orders, orderproducts, productimage, customers
WHERE orders.orderid = orderproducts.orderorderid
AND orderproducts.orderprodid = productimage.imageprodid
AND orders.ordcustid = customers.customerid
AND ordstatus = '11' group by orderid
ORDER BY orderid
so you can get the product names comma separated, in a column for a particular order

Categories