What's the best practice to handle multiple MySQL transaction? - php

I'm developing an order system with PHP + mySQL. There's a high chance that multiple users will create new orders with same product at the same time.
This is the scenario: in MySQL DB, there's a table named "inventory", in which all products' item numbers and available quantity are listed.
Now,
Product A's inventory is 500 pcs.
User1 is working on a new order with 300 pcs of product A, but he hasn't submitted yet. However, there's an AJAX script to send a query to table "inventory" and since the inventory qty is 500 pcs, so it returns 300 pcs as available for this order.
User2 is working on another new order now, while User1 still hasn't submitted his order. User2 wants 400 pcs of product A, and since 300 pcs from User1 has't been submitted, AJAX function returns 400 pcs are available for User2's order.
Now here's the problem. Either User1 or User2 submits his order first, the another user will not have enough quantity to fulfill his order as the result returned by AJAX.
I want to know what is the best (or normally) practice to handle this type of task.
I have thought about PDO transaction handling (not sure if it will work, have never used it, I'm quite new), or maybe should I just forget about AJAX but do the inquiry when user submit the form?
Also I had thought about putting a "check" button on the page then after the user finished inputting the order, they hit "check" to send an inquiry to DB then get the most 'updated' quantity, maybe it's soon enough before the user hits submit.
Thanks.

Thwo things you have to understand first:
There is no such thing like "PDO transaction"
Transactions are inapplicable here anyway.
What you actually need is simple reservation system. Or a notification one.
In case of reservation, you may mark 300 items as "reserved". Then all others may either content with remained 200 or wait till reservation gets released or stock refunded.
While an example of notification system you may see right here on this very site: in case there is a user who is working on the answer, and question happened to be closed, an ajax notification is shown to the user, saying he has not enough items to reserve anymore.

there are 2 ways:
1) you reserve the stock as user1 puts it in their basket
(and deal with timeouts / abandoned orders and moving stock back to inventory and a way to notify the users when items come back in stock)
this means that user2 can't add them if user1 has them.
(you could physically remove the number from the inventory, or you could add another column with 'reserved' in it - e.g. 200 in stock and 300 reserved)
2) you do the stock check + reserve when the user has begun the checkout process and notify the users if the items aren't in stock and you don't have to deal with abandoned orders as they haven't reserved the stock yet.
I have developed e-commerce systems based on both, and #1 is, imho the best - as a user I want to know if the things are in stock as I add them to my basket

This isn't a matter of what you're using to make your query (though using PDO is still a good idea.) When the user finally submits their order, your php script should perform an extra check that the requested amount is in stock. If not, the user should presented with an error that the amount of product is no longer avaiable.
Use ajax to check the stock periodically so the user gets a javascript notification when something in their order is no longer available.

Related

How to add, reduced amount of item, to its table, when user close browser tab in payment gateway

I have a situation for shop market, when user wants to pay, first a factor will create then redirect him to the payment gateway.
In factor creation, number of items that user is selected, reduce from stock number count of existence items, so if user close the payment gateway browser's tab, wanted items are reduced from stock items count and never returns.
How manage this situation for payment??
My Solution
I think a lot on that and come with this solution that create a reserved factors table to store current factor that is going to pay and when back from payment gateway, simply delete it.
If browser's tab was close by user then calculate that if time of reserved factor is more than payment gateway the delete it from reserved table and add reduced items number to stock number count.
I add this code to my construct (because I think this is right place to check for all items in reserved factor right before show items to user. This helps for items that are not available, to be available now) but in another hand I think if number of reserved factors in database are big enough, it might have a huge effect of loading performance.
SO what is the right solution for situations like this?
Can I have something like a schedule plan in MySQL to delete those records? or even in PHP?
OR ANY IDEA...
EDIT:
I do want a code base solution if any exists.
Can I have something like a schedule plan in MySQL to delete those records? or even in PHP?
Usually this sort of thing is done using your server's "cron" feature (or "Scheduled Tasks" if your server is running Windows). You can write a PHP script that clears these abandoned carts when run, and configure your server to execute that PHP script at regular intervals.
MySQL also has an "Event Scheduler" feature; I don't think that gets used very often, but it is an option.
...so if user close the payment gateway browser's tab, wanted items are reduced from stock items count and never returns.
This is the wrong way to look at this problem. Consider these scenarios:
User accidentally closes their browser, re-opens it, and tries to finish purchasing
User loses internet access and cannot finish purchasing... browser isn't closed
While it is possible to use the Beacon API in newer browsers to send an update when a browser is closed, for these reasons it's a bad idea.
You have two general options:
Option 1: Track the user/cart activity
Every time the user does something meaningful on the site, update their last active time on a record for their cart. If a user is still browsing the site and they have a product in their cart, keep it reserved there until the sale is complete or until they are no longer active for some period of time. For example, if they haven't been on the page in 15 minutes, release the reservation for the product. (Be prepared to reserve it again if they come back and the product is still available.)
Option 2: Don't reserve until purchase
Keep the item in-stock until it's actually bought. If at the time of purchase the product is no longer available, let the user know.
Which of these options you choose depends on your business conditions and the sort of stuff you're selling.

How to check the status of a database field changed after 3 days of its creation with php and mysql?

I am making an online shopping cart but I want to be sure that the products that you select are reserved for 3 days and when the time is up, return the total of products that the customer booked and update the status of the shopping cart, or also if it has generated A comment the admin receives a notice on your page as on facebook as when they like like one of your photos notifies you
how I can do it, I had thought of a trigger but how can I go back to the background or what is the correct way to do it?
There are about a million ways (okay, maybe tens) to solve this problem. For example, you can have a cron job that runs once an hour or whatever time period works for you. The job runs your PHP program and performs the actions that you want for out-of-date entries. Simply select the items that meet your criteria, remove them from the cart, and then notify the user in whatever way you want.

How prevent to buy one item by two customers

I'm selling some stuff on my website using paypal IPN + PDT. I always check how many items are in the stock before payment. After customer makes his order, he is redirected into paypal for make payment. When payment is completed I'm updating database about selling stuff, until this moment I had no problem becouse I was selling unlimited items. I'm not sure what should I do in case where I have for example 10 items for sell, for example in this scenario:
There is last item for sell. Customer makes his order and he is going to pay on the paypal but he didn't payed yet (website still showing that there is one item for sell ), meanwhile customer B see that there is one item left in stock so he is going to buy it too. in this scenario both customers will pay but only one (faster one) get his product.
What I must do to dont make this happen ?
I can't give you a code answer without seeing yours first, but here's how it could be done on paper :
When customer A clicks the "Pay" button, the item quantity is updated in the database
If the payment goes through, do nothing, if the payment doesn't go through (cancelled, incorrect payment informations, etc) then revert the quantity back to the original
This should work fine as long as you do a final "quantity check" when the user clicks the checkout button. Let's say that both customer A and customer B have an item X in the cart, and there's only one left. They can't both pay for the item, since your system would check the quantity before redirecting to Paypal, and as soon as one of the customers do click on the button, the quantity is updated to reflect the purchase.
Drown's answer is right, and I think it's better to reserve the items (reduce them from the stock) for a period of time, for example for 20 minutes.
You need a cron job or something to give back the unpaid items into the stock.
And if you are worried about crawlers you can set another cron job to check those users who have for example 3 unpaid orders with 20 minutes interval among their payments.
You probably can check this out through the orders table in your database. Maybe you need to block these kinds of users for a while or make a better decision about them.

InnoDB transactions and REST

I hope my question is suitable for this site and is not too broad but I am having trouble designing the following architecture:
I have two sites. Site 1 is responsible for transferring credits between users. Site 2 is responsible for providing these users with services/products which can be paid with the credits they own in Site 1.
Lets say I have 1000 credits on Site 1. I have a service/product which costs 50 credits on Site 2 and a user wants to purchase it with his amount of credits he owns in Site 1.
Both sites communicate with REST. So for example when a user wants to purchase a service/product Site 2 prepares its request and sends it to Site 1 which makes the transaction and confirms to Site 2 that the transaction was successful (e.g. the user had enough credits for the service/product and those credits were successfully transferred to the destination)
Now here's the tricky part. In Site 1 I have the following logic:
Begin transaction
update user set credits -= 50 where id = 1
update user set credits += 50 where id = 2
REST CALL (Site 2) Success
Site 2 response - OK, commit transaction
Commit
Since REST is a call to a different site the transaction might take some time to complete. In the mean time is the whole table locked for any transactions or are the rows for user 1 and user 2 locked? Is this the proper way to implement my logic? Am I missing something?
Thank you in advance.
This is in response to your question on Casey's answer:
Yes, as long as you do it like this:
Site 2:
Customer logs in.
Ask Site 1 for credit total & transaction history (GET request) for this user (user 1).
(Any awaiting transactions which receive 'transaction succeeded' responses are made available for download/dispatch)
Use credit total to enable "Buy" buttons for things that can be afforded.
Customer clicks a Buy button
generate a transaction ID unique to site 2, store in database along with details of who bought what, when they did so, with state = pending. tell user transaction has been received and they should be notified soon whether it was successful (HTTP 202 response)
POST purchase request to Site 1, including authentication (don't want forged requests to cause people to spend money they don't want to spend) and the transaction ID.
Site 1
validate authentication
verify that Site 2's transactionID has not been used before by site 2. if it has, return an error, if not:
Begin transaction
update user set credits -= 50 where id = 1
update user set credits += 50 where id = 2
insert into transactions remoteSiteID = 'Site2', remoteTransactionID = tID, user = 1
You would not need the remoteSiteID field if site2 is the only site using credits from site1
Commit
REST CALL (Site 2) Success
Site 2:
EITHER:
1. Receive REST success call, make purchase available for download/dispatch, display some message to user saying purchase processing complete. Update local transaction record, state=succeeded.
OR
2. Site 2 is down. Transaction success will be noted next time background polling process runs (which checks status of purchase requests awaiting responses) or next time customer logs in (in which case poll is initiated too--step 3 in first list)
If you have not received a response to a transaction, perform a GET using the transaction ID. If the response is an error, Site 1 did not receive the original request, Site 2 is free to repeat the transaction (POST) request. If the response is 'transaction failed' then the user didn't have enough credits, update transaction record on site 2 accordingly. if result is 'transaction succeeded' record that too.
if a transaction fails N number of times, or a certain period elapses since the user clicked the button (say 5 minutes) then Site 2 stops retrying the purchase.
Since you're using primary keys and not ranges, it should be row-level locking. There's also the concept of a shared vs exclusive lock. Shared locks allow other processes to still read the data while an exclusive is used in an update/delete scenario and blocks all others from reading it.
On the logic in general.. if there's really only one place storing the credits and one place reading them, how important is it to sync in realtime? Would 3, 5, or 10 seconds later be sufficient? If Site 1 is completely down, do you want to allow for Site 2 to still work?
Personally, I would restructure things a bit:
A user creates an account on Site 1.
The first time a transaction is done on Site 2, it validates the account exists on S1 and gets the number of credits.. and keeps it.
Whenever a transaction is done on Site 2, you check the local credit count (cache) first and if there are enough credits you return a 202 Accepted response code. It basically means "hey, we accepted this but aren't done with it yet."
You can immediately allow the user to continue at this point.
But at the same time you did the local credit check, you made another request to S1 with the actual transaction.
Hopefully, that service can give you a success/failure message and the update definitive/official credit count.
Using that, you update the local transaction status to 204 NO Content (success) and update the cache for the next time.
Since S1 is always returning the definitive current credit count, you don't have to worry about maintaining the credit count on S2 in a 100% accurate way.. you can just wait for it from S1.
If you're really nervous about it, you could have a job that runs every N hours that polls S1 requesting updates on every account updated during that N hours.

Dealing with two people buying a unique item in an online shop at the same time

I'm creating a simple online shop with PHP integrated with PayPal that sells unique items. What I'm wondering is how other shops deal with multiple people attempting to go through the payment process with the same item.
This is my current draft strategy:
Items have three status types: available, on hold & sold.
As a user moves to the PayPal payment page it checks the status of all the items in the cart to ensure they're available. It also sets the item's status to "on hold" until they either come back after payment is confirmed or it times out (10 minutes? Not sure what this should be).
Is this standard practice or is there a more practical way I should be going about this?
Thanks in advance!
Have a look at Dell's UK outlet. When someone adds a system to their shopping basket it is held and not available to other customers. If it isn't purchased, the item is removed from the basket after 15mins of inactivity and is then available to other customers.
I would say the first part of your strategy is correct - as you move to the payment page, flag all the products as 'on hold'
When the user has finished the payment, you will get a postback from Paypal which lets you know if the authorisation was successful or not (and possibly also allows you to check the CSC/CVV2 result), and at that point you have the option of either accepting the payment, or rejecting it.
On receipt of the postback you should also check whether the items are still on hold. If they have timed out you can reject the payment and display a message 'sorry - timeout exceeded' or somesuch.
This method also allows you to work out an ideal timeout period if you keep track of how often customers run into the timeout, so you can extend the timeout from (eg) 5 to 10 minutes if too many are timing out, or shorten it if none are timing out.
This is a fairly common issue with fixed inventory systems such as venue, transport/airline tix etc.
I like the airline model where once you get the itinery you want and click select, you get a page with passenger info with a message saying, seats on hold and you now have xx(10/15) minutes to complete the purchase. Everything becomes explicit at that time. For other unique/one of a kind item, I'd think a message on any page, that the user clicks on, saying you have xx(mins) remaining to complete the purchase would be a big motivator for "on the edge" buyers !
woot.com is notorious for this problem but their solution works well. After payment information is verified the user is brought to a page with a small amount of text saying something like "your order is in, we are verifying inventory".
It looks like the paypal API has a "RefundTransaction" message so something like that might not be possible. But the user experience could be awkward if your going to the paypal website then coming back to your site.
This is much like booking theatre tickets or similar online and yes the way you describe is generally the way it works. At some point the item is "reserved" in the system and either the customer completes the transaction or the item is released after some time for others to buy.
Of course at what point you reserve the item (when it's added to the cart, at the point you send them off to pay etc) is up to you. I would expect putting it in the cart would be the best choice as it makes it less likely someone will build up a basket of stuff only to find half of it is no longer available at the checkout.

Categories