the code may execute fine, but that doesn't mean that it is working fine.
the issue is this:
you are sending the email and saving the order to the database before the transaction has happened.
your redirect page is storeing the order and sending the email before the user goes to paypal, once they get to paypal, they select the payment method, then complete the order.
paypal then puts the transacrtion into a queue and will process the transaction on a first come fitst served basis.
what heppens if the transaction fails?
What if the user gets to paypal and decides not to process the order?
you have already stored it to your DB and already sent the receipt.
when paypal processes the transaction, it can be set to make an IPN post to your site with the results.
with paypal standard you should be using the IPN page to store the order details and send the receipt email if the transaction is successful.
or, you could use paypal express which is a real time gateway using express checkout, he user is directed to paypal to select the payment method, then directed back to your site where the confirm the transaction, when the transaction is confirmed, if it is successful, the pp_confirm page stores the order details and sends the receipt, there is no nee to configure the IPN page.