Tarik Kaoukab Tarik Kaoukab - 6 months ago 13
jQuery Question

how to modify a database (mysql) and restore it after 5minutes?

I would like to decrement a value (number of product in stock) when a user clicks on a button "add to cart", and restore the value to the initial value after a time (let's say 5minutes) ?
P.S : im using PHP jquery and ajax.

Answer

You can use PDO (php communication with MySQL). One such example would be to decrease the value in the database with a prepared statement to improve performance (and security of course):

$sql = "UPDATE myTable SET number_of_products = number_of_products - :quantity WHERE product_id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':quantity', $quantity);
$stmt->bindParam(':id', $id);
$stmt->execute();

Then, since you already prepared the statement, you could revert this value as follows (without having to re-declare the whole sql statement)

$stmt->bindParam(':quantity', -$quantity);
$stmt->bindParam(':id', $id);
$stmt->execute();

If you wanted the second script to take place after 5 minutes, you could have a queue system implemented that has a delay of 5 minutes for instance. There are also functions that can be used to sleep for 5 minutes, however it would be very unpractical to have that function run on the same page as the user (unless you plan on using it in a separate script) since the user would literally have to be on the same page for 5 minutes waiting.

Comments