Site icon WDB24

PHP Shopping Cart – Display Products from Database


In this third tutorial of the series we will see how to display product from database. As I mentioned before I will be working on the frontend of the shopping cart. So I just added products manually into database table. Also I have created a separate table for product images in previous post.

Before jumping into the coding let’s note down the steps which we will follow:

Display Products from database:

In this shopping cart project, product listing will be our main page. So let’s create index.php page and add some code.

As you can see in above code that I have added session_start() function at very first line. It is because we will be saving cart in php session. After that I have included config.php and helpers.php files which I created in our previous tutorial. Then I wrote a mysql query using PHP PDO and fetch all products and saved in $getAllProducts. $db is the database connection object. After that I have created $pageTitle variable which holds title of the page and it will use in header.php. In the next line of $pageTitle I have included header.php file.

Now let’s move to html part

As you can see in the above code that I started foreach loop after div. Foreach loop is iterating on each record that is under $getAllProducts array. PRODUCT_IMG_URL is a constant that I created in config.php file. After that I am rendering bootstrap 4 card code and passing product data in HTML tags. All href tags in the pointing to single-product.php page with product id as a query string. In the end I included footer.php file from layouts folder.

Also read:

Exit mobile version