Created
October 19, 2020 10:15
-
-
Save AriffAzmi/f64535e6acdcd261df8782e4172b9574 to your computer and use it in GitHub Desktop.
Sample parallel test for php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
try { | |
$db = new PDO('mysql:host=127.0.0.1;dbname=parallel_test', '', ''); | |
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); | |
$requested_stock = (int) $_REQUEST['requested_stock']; | |
$item_id = (int) $_REQUEST['id']; | |
$product = $db->prepare("select stock from items where id = ? limit 1 for update"); | |
$product->execute([ | |
$item_id | |
]); | |
$product = $product->fetchAll(PDO::FETCH_OBJ); | |
if ($product[0]->stock > $requested_stock) { | |
$update_stock = $db->prepare("update items set stock = ? where id = ? limit 1"); | |
$update_stock->execute([ | |
($product[0]->stock-$requested_stock), | |
$item_id | |
]); | |
echo "Product updated."; | |
} | |
else { | |
echo "Unsufficient stock."; | |
} | |
} catch (PDOException $e) { | |
die($e->getMessage()); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment