Update stock value with mysql - mysql

Now i have this sql update code:
$sql = "UPDATE products SET stock = stock - '$quantity' WHERE product_id = '$id'";
I have some problem with this. It works, but if the stock value in the table is smaller, than the quantity in the webshop cart, it will update the stock field to a minus value.
I know, that there is a function in mysql for this, that will only update it to 0, and not to minus. Whats that function, or how should i do this?

You can use case
UPDATE products SET stock
= case
when stock > '$quantity' then stock - '$quantity'
else 0 end
WHERE product_id = '$id';
Be sure that your variables $quantity and $id are checked to be sure that they are numeric to avoid SQL injection.

You can use the MySQL IF Statement for this. First check if stock - quantity is greater than 0 then return the value, else return 0.
UPDATE products
SET stock = IF(stock - '$quantity' > 0, stock - '$quantity', 0)
WHERE product_id = '$id';

You could use the GREATEST function to get the largest value of your existing calculation or 0, then if the current calculation is negative, 0 will be inserted.
I haven't tested this, but this should work:
$sql = "UPDATE products SET stock = GREATEST(stock - '$quantity', 0) WHERE product_id = '$id'";
I'd just be careful you aren't prone to SQL injection here as you are passing $quantity and $id directly to the query string and if this is from a $_POST or $_GET request variable then the query can be manipulated.

Related

How to assign column value to a variable within mySQL script ?

I have the following script but it returns null all the time.
SELECT
#PRICE_LARGE_PRICE = PRICE_LARGE_PRICE,
#PRICE_SMALL_PRICE = PRICE_SMALL_PRICE
FROM
prices
WHERE
PRICE_LISTING_ID = 60;
SET #ITEM_PRICE = (CASE Size WHEN GivenLargeSizeName THEN #PRICE_LARGE_PRICE
WHEN GivenSmallSizeName THEN #PRICE_SMALL_PRICE
ELSE null
END);
The issue here is
#PRICE_LARGE_PRICE = PRICE_LARGE_PRICE,
#PRICE_SMALL_PRICE = PRICE_SMALL_PRICE
table returns PRICE_LARGE_PRICE & PRICE_SMALL_PRICE correctly but the assignment does not work. Hence CASE fails.
Any help is appreciated.
You need to use SELECT ... INTO:
SELECT PRICE_LARGE_PRICE, PRICE_SMALL_PRICE
INTO #PRICE_LARGE_PRICE, #PRICE_SMALL_PRICE
FROM prices
WHERE PRICE_LISTING_ID = 60;
Note that you need to ensure that the query only returns one row of data, using LIMIT 1 if necessary.
SELECT
#PRICE_LARGE_PRICE:=PRICE_LARGE_PRICE,
#PRICE_SMALL_PRICE:=PRICE_SMALL_PRICE
FROM
prices
WHERE
PRICE_LISTING_ID = 60;
just add colon before equal sign in mysql

rollback transaction based on condition

I want to abort batch sql query transactions if column value is less than or equal to user's input value and alert user.
Here's what happens:
available_qty value is subtracted from user's input qty value and the value is updated in food_menu table.
user's order records are inserted into food_order table.
Here's my query:
foreach($menuData as $item=>$qty)
{
if(empty($qty) || $qty == '0')
continue;
$sqlArray[] = "INSERT INTO food_order
(user_id, item_id, quantity, order_type, updated_on, updated_by, created_by, created_on)
VALUES ($uid, $item, $qty, '$menu_type', NOW(), $uid, $uid, NOW())";
$sqlArray[] = "UPDATE food_menu SET available_qty = IF($qty >= available_qty, available_qty - $qty, available_qty) WHERE item_id = $item AND type = '$menu_type' AND DATE(updated_on) = CURRENT_DATE";
}
return (boolean) $this->db->exec($sqlArray);
if $qty value is greater than available_qty field value, I want to abort the whole series of transactions in $sqlArray[].
Can I do that in the query itself?
I think a much better approach is to check the available quantity with remaining quantity before the start of your insert and update statement. But for the sake of information you can try the following:
Create a before update trigger on food_menu table. In the trigger check the available quantity of it is negative meaning the order quantity is more than available quantity then use the SIGNAL statement to raise an error which you will have to catch in your code and do the rollback and show appropriate message to the user.

MySQL sql ignoring WHERE condition

I have the following problem - I am coding an e-commerce website, that has promotions for a certain period of time. When time elapses promotion changes its corresponding database active value to 0. When I check for promotions the first condition is that active=1, but at some cases MySQL is ignoring it.
Here is an example of my most recent problem:
$productPromotion = $db->getResults('*', TABLE_PROMO, "active = '1'
AND (discount_subject = 'all_orders'
OR discount_subject_product = ".$values['product']['id'].")
OR (discount_subject = 'category'
AND discount_subject_category = ".$categoryId[0] . ") ORDER BY id ASC");
$db->getResult is a custom function that takes 3 parameters - What, Table and Where.
The problem is that it is returning promotions that are already expired and have active=0. Where is the problem with my sql?
You have to add brackets arround or
$productPromotion = $db->getResults('*', TABLE_PROMO, "active = '1'
AND
((discount_subject = 'all_orders' OR discount_subject_product = ".$values['product']['id'].")
OR (discount_subject = 'category' AND discount_subject_category = ".$categoryId[0] . ")) ORDER BY id ASC");
Also learn about prepared Statements to prevent SQL-injection

Update multiple values in WHERE MySQL

I want to update multiple itemIDs with the same status. I know that this is imposible with mysql_query but I can't figure out a way to get this working.
$upd = "UPDATE booking SET status='$status' WHERE itemID='$itemID', '$itemID2'";
$retval = mysql_query($upd, $con);
Note: The itemIDs are inputted by user in prev page like this
$itemID= $_POST["itemID"];
$itemID2= $_POST["itemID2"];
Use IN clause as like:
WHERE itemId in ('$itemID', '$itemID2');
instead of WHERE itemID='$itemID', '$itemID2'
Use IN
$upd = "UPDATE booking SET status='$status' WHERE itemID IN ('$itemID', '$itemID2')";

How to get 0 rows updated query/data from Oracle in PHP?

Suppose I am firing query that will upadte data if all value are available else will run with 0 rows updated. So How to get those 0 rows updated query/data from Oracle db in PHP?
In my script, I am updating table if item_flag is N, item_name is stored in $sku so checking with that & site_code is in $final_code so all these in where condition.
so if update query runs successfully with value updation then I am taking execution result in $result & updating status of Mysql table.
But what happened is when there is some data not present say $sku in update query then query runs with 0 rows updated...& likewise it will move to if($result) loop & update the status which I don't want as practically data/row is not get updated...
so How to get 0 rows updated query/data from Oracle in PHP?
--------------some code above--------
$query_ora_update = "UPDATE ITEM_DETAILS SET ITEM_FLAG= 'Y', LAST_UPDATE_DATE = sysdate WHERE ITEM_NAME = '$sku' AND SITE_CODE = '$final_code' AND ITEM_FLAG = 'N' ";
$parse_result = oci_parse($conn,$query_ora_update);
$result = oci_execute($parse_result);
oci_commit($conn);
if($result)
{
$query_update_alert = "UPDATE product_creation SET alert_status =1 where
entity_id = $entity_id and sku = '$sku' and alert_status = 0";
$result_query_update_alert = mysql_query($query_update_alert);
}
-------------------------------
Use oci_num_rows function. Documentation Here
EDIT: Example Code
$parse_result = oci_parse($conn,$query_ora_update);
$result = oci_execute($parse_result);
$row_count = oci_num_rows($parse_result);
oci_commit($conn);
if($row_count > 0)
{
-------------------