Site icon WDB24

PHP Shopping Cart – Checkout code with validation


This is our last tutorial of PHP Shopping Cart series. In this tutorial we will see checkout code with backend validation. Right now I will use cash on delivery as a payment method. But in future I will try to add checkout with Stripe and Paypal at least.


Above html code is consist of left and right columns. In right column there is cart details and in left column there is checkout form. I am using $_SESSION['cart_items'] array to print cart items. Checkout form has 8 input fields and almost all fields have condition to show submitted data. Also there is a condition of $errorMsg to print error messages.


Above PHP code starts with session_start() that is must function for shopping cart. After that I am checking cart items in session. If there is no cart item in session, user will redirect to product listing page. Next I have included config and helpers files. Config.php file has PDO connection and in helpers.php, I have written helper functions. Then there is submit condition that would check form submit event. Under form submit condition there is another isset() condition which is checking all the required inputs and their values. If any of the required input empty, user will receive validation error.

After that there is email validate condition. If email validation fails, code will return an error. Otherwise in the else clause, first I saved all the input data into their respective variables. validate_input() is a custom php function that I created in helpers file. And then I wrote a SQL statement to insert data in orders table. If data will insert in orders table then order items will be added in order_details table and total price will also updated in orders table. If all goes well, user will be redirected to thank-you.php page.

Also read:

Note: Demo link will redirect you to home page. You need to add item in cart to view checkout page.

Exit mobile version