Skip to content

Instantly share code, notes, and snippets.

@AriffAzmi
Created October 19, 2020 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AriffAzmi/f64535e6acdcd261df8782e4172b9574 to your computer and use it in GitHub Desktop.
Save AriffAzmi/f64535e6acdcd261df8782e4172b9574 to your computer and use it in GitHub Desktop.
Sample parallel test for php
<?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