For someone who search an exemple with PDO
Quickly ...
<?php
/**
* Class Set_quantity_product
*/
class Set_quantity_product {
/**
* Set_quantity_product::update_quant_prod( $id, $number, $to_do );
*
* @param {int} $id a product id
* @param {int} $number a number to increment or decrement for a value in DB
* @param {str} $to_do 'incr/decr'
* @return {void} increment or decrement but always return 0 if quant < 0
*/
public static function update_quant_prod( $id, $number, $to_do ){
$DATA_BASE = new PDO('mysql:host='.$YOUR_HOST.';dbname='.$YOUR_DB_NAME.';charset=utf8', $YOUR_USER_NAME, $YOUR_DB_PASSWORD, array( PDO::ATTR_PERSISTENT => false));
// Note:
// UPDATE products
// SET quant = GREATEST( 0, quant+:ope )
// WHERE id = :id
// increm or decrement but do nothing if quant is > quant in DB
// pass quant number to affect to negative for decrement
$number = ( $to_do == 'decr' ) ? $number*-1 : $number;
// UPDATE ONE PROD. QUANT. 'ope' -> calcul operation
$ARR_pdo = array( 'id' => (int) $id,
'ope' => $number );
$sql = 'UPDATE products SET
quant = IF(quant+:ope >= 0, quant+:ope, 0) WHERE id=:id';
// prepa. SQL
$request = $DATA_BASE->prepare($sql);
// exec. request
$request->execute($ARR_pdo);
// PDO closeCursor
$request->closeCursor();
// return true for test
return true;
}
/**
* Set_quantity_product::update_quant_prod( $id, $number, $to_do );
*/
}
/**
* Class Set_quantity_product
*/
?>
Use : ( consider you have a product with an id=42 )
Set_quantity_product::update_quant_prod( 42, 5, 'decr' );
if your quant in DB is 6 -> this set the value at 1
if your quant in DB is 5 -> this set the value at 0
if your quant in DB is 4 -> this set the value at 0