mysqli update with calculation in query - php

In our cart process we don't want to remove items from the store inventory until after the payment gateway has returned a approved code for the credit card purchase. Thus assuming the payment was approved we need the cart items to deduct from the inventory.
In a mysqli UPDATE query how if possible can i write it so that the new value being set is the result of the rows current value - the quantity stored in the carts Item_qty field?
mysqli_query($con,"UPDATE table1 SET Qty='`**current-value**` - $proc[Item_Qty]' WHERE buyer='$user'");
I do understand that I can accomplish this using multiple queries, perform some math and then write the value back to the database, but I am hoping there is a cleaner way with less code by doing all in a single mysqli query.

You can use current values of the table in an update.
mysqli_query($con,"UPDATE table1 SET Qty = Qty - $proc[Item_Qty] WHERE buyer='$user'");

Easy. You can use the field itself in the calculation:
UPDATE table1 SEt Qty=Qty - $proc[Item_Qty]
^^^--- this is 100% perfectly valid

This should do it:
$query = "UPDATE table1 SET Qty = Qty - $proc[Item_Qty] WHERE buyer='$user'";
You are simply, using the field name again to get its current value.

Related

Change multiple MySQL fields with single query - product code sales

I have a site with products I sell and each product has its own product code. The problem is that recently we changed all product codes to all products.
Because all sales inserted in MySQL before today used the old product code, when I try to get a report to see how many of one product has been sold system find 0 because it looks for the new product code while older sales was inserted with the old one.
Solution:
Even if it is a pain there is no other way than updating all products sold and inserted in MySQL updating the old product code with the new one this way it will work fine.
I need to update like this:
$update = mysqli_query($database, "
update `sales` SET code = 0001 WHERE `code` = '4574645448458'
");
The only problem is that it updates only the first product with this product code but I have houndreds of products sold with the same product code...
How to solve this in some bulk way?
examples of what I will change:
code 4574645448458 for 0001
code 4574645448459 for 0002
and so on
Here is an example of the suggestion from Marc B.
Use a prepared statement and execute it with each pair of "old/new" values.
A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.
For example:
// define an array with all of the code changes as "key/value" pairs
$changes=array(
'4574645448458' => '0001',
'4574645448459' => '0002',
....
);
// define the query string with placeholders
$sql="UPDATE `sales` SET `code`=:new_code WHERE `code`=:old_code;";
// prepare the statement and set up variables to be bound upon execution
$q=$database->prepare($sql);
$q->bind_param(':new_code',$new_code);
$q->bind_param(':old_code',$old_code);
// iterate through "changes", defining the "old" and "new" values for each code change
// execute the prepared statement with each pair of values
foreach ($changes as $old_code => $new_code) {
$q->execute();
}

PHP and SQL maths

This part of PHP and SQL is totally new to me where I need to use maths to update a table.
I currently have a table avis_credits with one row only in this table
The table deducts credits as the user uses the system from qty_credits, but i want to be able to add additional credits to his account as per example:
Client has currently 10 credits left he purchases 100 credits so the system must take the current credits and add the 100 to it giving me the 110 credits. I am doing this currently manual adding it my side and updating the table with this expresion.
"UPDATE avis_credits SET credits='$qty_credit'";
What I would like is that the system looks up the current credits and adds the new credits to the row.
I have tried this
"UPDATE avis_credits SET credits='<?php echo qty_credit?> + $qty_credit'";
But it is not working at all. Is it because I am trying to do too many functions in the one string? Or is it because The maths equation is wrong as I have no idea how to write it?
On your first query you're not doing any math you are purely changing it to the value of your variable:
"UPDATE avis_credits SET credits='$qty_credit'";
So credits becomes the value of $qty_credit.
On your second query <?php echo qty_credit?> this is wrong, you're trying to open another php tag on an already open one and you don't use the $ on the variable and then you try to sum the variable so it gives you an error.
"UPDATE avis_credits SET credits='<?php echo qty_credit?> + $qty_credit'";
This will sanitize your input and sum the value of credits with the addition of value of your variable $qty_credit:
$sql = sprintf("UPDATE avis_credits SET credits = credits + '%s'",
mysql_real_escape_string($qty_credit));
As a side note, you may want to specify an ID of the account you want to deposit the additional credit otherwise the above rule will increase that credit for ALL rows.
$sql = sprintf("UPDATE avis_credits SET credits = credits + '%s' WHERE id = '%s'",
mysql_real_escape_string($qty_credit),
mysql_real_escape_string($id));
SQL support arthmetic operations.
So you can do the following:
"UPDATE avis_credits SET credits=credits + $qty_credit";

Multiple update to the same row in database

I'm making a Billing system with some friends, it works this way:
The customers make calls.
The customers hangup the call.
The price of the call is calculated.
The price of the call is reduced from the customer's credit.
We decided to make the following:
Get the user's balance and store it in a variable, $balance, after do a $balance = $balance - $callprice, and finally update the database.
The problem is that the customer can make simultaneous calls, and if two calls finish at the same time, and one of them gets the value on the database before the other script had updated the new balance... one of the calls will be lost. I'm using php.
Any idea how can I do it?
Thanks, and sorry, I have a poor English...
The problem is it looks like you're trying to use two SQL statements to update the user's balance: One to SELECT the user's balance, then another to UPDATE the user's balance after the balance is subtracted using PHP.
You could do it all in one operation and eliminate the possibility of race-conditions:
UPDATE users
SET balance = balance - <callprice here>
WHERE user_id = <user_id here>

Mysql Insert Order Number By VARCHAR Field

I have a question about inserting row order number by spesific order type.
Products table has OrderNumber field. I want to programaticly add new line to appropriate OrderNumber by its name. If the reference column would be integer it has to be easy like that
update products set OrderNumber=OrderNumber+1 where Price>555
Is there similar way for varchar field like
update products set OrderNumber=OrderNumber+1 where Name>'bla%'
Thank you
You can use STRCMP('text', 'text2')
update products
set OrderNumber=OrderNumber+1
where STRCMP(Name, 'bla') = 1;
I missunderstood your point. Can you try something like this?
SET #rownum:=0;
update
set OrderNumber=#rownum:=#rownum + 1
from products
order by Name;
You can simply run an update query with a sequential number like in here
Sounds like a bad design. Why not simply have a plain-jane auto_increment field and order by that? Every new record would by defnition have a higher ID than any of its predecessors.
you mean something like update products set OrderNumber=OrderNumber+1 where Name like 'bla%'

mysql - update two records at once

Using PHP's msqli is it possible to update two records with one query?
First I do a SELECT to check that $pay_user has enough game currency in his account, if he does then I do the following...
My update query is:
"UPDATE account SET money= money - ".$money." WHERE User_id=".$pay_user
"UPDATE account SET money= money + ".$money." WHERE User_id=".$recieve_user
It is transactional to stop dirty read's.
I was hoping to save on a query and call it as one... is it possible?
Since the two where clauses are not the same, you cannot combine these queries into one statement.
You can mark it as a TRANSACTION so they both execute at the same time.
refer to http://dev.mysql.com/doc/refman/5.0/en/update.html
code sample
update account a1, account a2
set a1.money = a1.money - $money , a2.money = a2.money + $money
where a1.user_id = $pay_user and a2.user_id = $recv_user
I recommend using a stored procedure to do this. it will be one call from php, and if it fails in the middle the SP should issue a rollback.

Categories