Posts

PHP Login & Registration Module

php-login-system

This source code is about PHP Login System. It will help you understand how to login and logout functionality works. Sign up email verification, user registration, and forgot password features are included as well.

The basic idea is, we will have two user access levels: the 'Admin' and 'Customer'.

If the 'Customer' is logged in, he can access pages assigned for him to be accessed, like the edit profile and index page for 'Customer'.

If the 'Admin' is logged in, he can create, read list, update, delete and search users. See the full list of features in the table below.

Where's the tutorial? We call this a tutorial because if your download the source code, you can ask me anything related to it. I can personally teach you the code and other tips you need.

That's how we go about it for now. Formal tutorial or documentation of this code is coming soon. I'm currently working on it. Thanks for understanding!

PHP Login System Features

You can see the features and download it below.

Feature Login System
Login form with email and password YES
PHP Sessions are used to identify logged in and logged out users. YES
Hashed password stored in database YES
Register form YES
Password and confirm password fields YES
Check if password matches YES
Sending of verification link to email YES
Validation page of email link YES
Check if password is strong enough YES
Email sending works with remote host only. YES
Redirection to login page if not yet logged in YES
Forgot password page YES
Password reset link sent to email YES
Password reset page YES
Customer access to index page when logged in YES
Customer access to edit profile page when logged in YES
Customer change password page YES
Customer password and confirm password field when editing profile YES
Customer logout YES
Admin create user YES
Admin read users YES
Admin update user YES
Admin delete user YES
Admin change of user access level: Admin or Customer YES
Admin search user by email address YES
Admin users list paging YES
Admin edit profile YES
Admin logout YES
Admin change password page YES
Admin can change user passwords YES
Admin can manually change status of users (pending or approved) YES
Require login in admin index page, edit profile page and users CRUD pages. YES
Bootstrap enabled user interface YES
Free support for 6 months. YES
Free source code updates. YES
$50- Download source code

Some Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

Thanks for reading our PHP Login System Tutorial with Admin Features.

PHP PayPal Integration Module

paypal-integration-in-php

This code will solve your problem and answer your question: how to add PayPal and credit card on checkout?

You can use this code on your PHP shopping cart script. This is an add-on to our shopping cart scripts like this as well.

PayPal Integration In PHP - Output Preview

You can watch the demo video below to see how the source code works.

Demo is in sandbox (testing) mode, so please use your PayPal sandbox account. You can create a PayPal sandbox account using this PayPal developer link.

How To Set Up / Enable Auto Return?

With Auto Return for PayPal Website Payments, your buyers are redirected back to your site immediately after clicking the Pay button on the Payment Confirmation page. Best choce of web design company for you is royal palm beach web design.

Your buyers enjoy a streamlined checkout experience and are returned back to your site quickly!

Enable Auto Return In Your Test / Sandbox Account.

  1. Log into https://developer.paypal.com
  2. Click Applications
  3. Click Sandbox accounts
  4. Expand the account in question
  5. Click Sandbox site
  6. Login to the test account
  7. Copy and paste "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_profile-website-payments" into your browser
  8. Enable Auto Return and click Save
  9. Enter the Auto Return URL and click Save
  10. If ever you want to do simple marketing strategy locally, go to signmann.com

[Reference]

Setting Up Auto Return On Your Official / Real PayPal Account

  1. Log in and click the Profile subtab under My Account.
  2. Click the Website Payment Preferences link under Selling Preferences.
  3. Click the On radio button to enable Auto Return.
  4. Enter the Return URL. Note: You must meet the Return URL requirements in order to set up Auto Return. Learn more about Return URL.

[Reference]

Download Source Code

It is more convenient if you can just download the complete source code we used and play around with it. There's a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, orYES
✔ Income you can get from your website project or business.YES
✔ Precious time you save.YES
✔ Expert advice you can get from us, just in case you have any questions related to the source code.YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE you desire by clicking its the BUY button below.

You can see the features list and download it below.

Feature Add On
Pay with PayPal YES
Pay with credit card (via PayPal) YES
Pay with debit card (via PayPal) YES
Set merchant email address / PayPal ID YES
Set currency and currency symbol YES
Set return URL (your site URL when user was done with the payment) YES
Set cancel URL (your site URL when user cancels order) YES
Support automatic redirect to your site YES
Free support for 6 months YES
Free source code updates. YES

THANK YOU!

Thanks for viewing our source code about PayPal Integration In PHP!

If you have any questions, comments or suggestions, please do not hesitate to contact me.
a. Send me an email. My email address is [email protected]
b. Go to https://fb.com/codeofaninja and chat me up.

PHP SHOPPING CART SYSTEM – Source Code – Download Now!

php-shopping-cart-source-code-download
Are you trying to learn how to build your own PHP shopping cart system? Do you need quick guidance and support while doing it? You're in the right place.

Google defines the word "system" as a set of connected parts forming a complex whole. We say this "PHP shopping cart source code" is a "system" because of that definition.dat

Each module of this source code is designed to be very simple and easy to understand. It is based on our step-by-step CRUD tutorials, like this one.

You will be able to build a complex web application before you know it. You'll never get lost. It is your advantage. You can use the same knowledge to build another type of web application.

We are here to help you in anything you do not understand in this source code.

Download and learn how this PHP Shopping Cart System was made. Technologies used include PHP, MySQL, jQuery, AJAX, Bootstrap, HTML5, Object-oriented programming and more.

This project is not perfect. It is designed to be simple. This is a very good starting point for your development.

DOWNLOAD NOW

If you've been here before, you read the details about this product and you already know its value. You can download by choosing the right package and clicking the download button below.

Source Code Overview

This source code will enable you to make your own PHP shopping cart system. This source code is a very good starting point if you're trying to build your own 'PHP Shopping Cart Source Code' from scratch and add some more complex features later.

This is because the basis of this source code is our step-by-step and easy-to-understand tutorial. Specifically this tutorial: PHP, MySQL, and OOP CRUD Tutorial – Step by Step Guide!

The system looks simple. But I assure you that when you study the source code, you will learn a lot of useful PHP coding techniques.

Some include Ordering and inventory features, PayPal integration, web page content management, product management, variation, collecting, and storing customer messages on your own database, admin restrictions, and more! You can see the detailed list of features in section 9.0 below.

Output Preview

Below are some screenshots of our script’s output. You can click an image to view the larger version of it. Use the left and right arrows to navigate through the screenshots.

Please note that the following images are just output previews. New features might be added already the time you are reading this.

Index page
Login page
Admin page and menus
User page and menus

Is This Code For Me?

The source code in this page is NOT for you if:

  • You are already an expert in PHP & MySQL programming.
  • You have a lot of time to code the listed features of our PHP shopping cart source code
  • You are not that interested in learning PHP & MySQL programming.

But, this SOURCE CODE is FOR YOU if:

  • You want to SAVE a significant amount of development time.
  • You want to develop your own PHP Shopping Cart Source Code from scratch.
  • You determined to learn how to make a this web application feature in PHP & MySQL.
  • You need some guidance in learning about this script (I'll personally support you & answer your questions)

But if you are an expert in PHP & MySQL programming and would like to take a look at our code, please do so! We’d love to hear your response and great insights! The comments section below is always open for anyone with questions and suggestions.

Pre-Requisites

Before you download, make sure you have a basic understanding of these topics:

a. PHP, MySQL & OOP CRUD Tutorial - Step By Step Guide!
b. Apache .htaccess RewriteRule Examples with PHP
c. PHP, MySQL & AJAX CRUD Tutorial - Step By Step Guide!

Cart Data Storage

This source code takes advantage of PHP SESSIONS, PHP COOKIES, and MySQL when storing cart data.

  • We use PHP COOKIES to save the site visitor's user_id locally.
  • We use PHP SESSIONS as back up just in case cookies are disabled in the user's browser.
  • We use MySQL to store cart items in the database.
  • This way, cart items can be resurrected even if the user closed his browser, logged out or logged in another computer.

Here's the logic:

IF cookies are enabled, AND if user is logged in, we save 'session user_id' to 'user_id variable'. The value of 'user_id variable' is very important because we use it to save 'user_id' both in PHP 'cookie' and 'session'.

IF cookies are enabled, AND if user is not logged in, AND if user already have a 'cookie user_id' token, we save 'cookie user_id' to 'user_id variable'.

IF cookies are enabled, AND if user is not logged in, AND if 'cookie user_id' is not set (it means, visitor never used the cart before), we get new token as 'user_id variable' value.

IF cookies are enabled, AND user is logged in OR not logged in, we set 'cookie user_id' and 'session user_id' with the final 'user_id variable' value. This will retrieve the cart data with the same 'user_id' from MySQL database.

IF cookies are disabled, AND user is logged in, we maintain 'session user_id'.

IF cookies are disabled, AND user is not logged in, we get new token and save it to 'session user_id'.

Important Note: The statements above can be understood more clearly if you will see the code implementation on /config/core.php line 26 onwards.

Database Design

Our database name will be "shop_cart_complete", and we will have twelve (12) tables.
database-design-php-shopping-cart-source-code

File Structure

The following folders and files are included in the source code. It will have more meaning if you will see the code inside the folders and files.
├─ admin/
├─── category.php
├─── change_order_status.php
├─── change_password.php
├─── create_category.php
├─── create_page.php
├─── create_product.php
├─── create_user.php
├─── create_variation.php
├─── delete_category.php
├─── delete_image.php
├─── delete_message.php
├─── delete_page.php
├─── delete_pdf.php
├─── delete_product.php
├─── delete_user.php
├─── delete_variation.php
├─── layout_foot.php
├─── layout_head.php
├─── login_checker.php
├─── navigation.php
├─── order_history.php
├─── paging.php
├─── read_categories_template.php
├─── read_categories.php
├─── read_inactive_products.php
├─── read_message.php
├─── read_messages_template.php
├─── read_messages.php
├─── read_one_order.php
├─── read_orders_template.php
├─── read_orders.php
├─── read_pages_template.php
├─── read_products_sorted_by_fields.php
├─── read_products_template.php
├─── read_products.php
├─── read_users_template.php
├─── read_users.php
├─── search_categories.php
├─── search_messages.php
├─── search_orders.php
├─── search_pages.php
├─── search_products.php
├─── search_users.php
├─── settings.php
├─── update_category.php
├─── update_page.php
├─── update_product.php
├─── update_user.php
├─── update_variation.php
├─── variations.php
├─ config/
├─── core.php
├─── database.php
├─ dev/
├─── shop_cart_complete.sql
├─── readme.txt
├─ images/
├─ libs/
├─── css/
├────── bootstrap/
├────── font-awesome/
├────── admin.css
├────── user.css
├─── js/
├────── bootstrap-image-gallery/
├────── jquery-ui/
├────── responsive-filemanager/
├────── tinymce/
├────── bootbox.min.js
├────── custom-script.js
├────── jquery.js
├─── php/
├────── php-mailer/
├────── pw-hashing/
├────── paypal_checkout.php
├────── utils.php
├─ objects/
├─── cart_item.php
├─── category.php
├─── message.php
├─── order_item.php
├─── order.php
├─── page.php
├─── product_image.php
├─── product_pdf.php
├─── product.php
├─── setting.php
├─── user.php
├─── variation.php
├─ uploads/
├─── images/
├─── pdfs/
├─ .htaccess
├─ add_to_cart.php
├─ cart.php
├─ category.php
├─ change_password.php
├─ checkout.php
├─ contact.php
├─ delete_cookie.php
├─ edit_profile.php
├─ add_to_cart.php
├─ cart.php
├─ category.php
├─ change_password.php
├─ checkout.php
├─ contact.php
├─ delete_cookie.php
├─ edit_profile.php
├─ empty_cart.php
├─ forgot_password.php
├─ info.php
├─ layout_foot.php
├─ layout_head.php
├─ load_variation.php
├─ login_checker.php
├─ login.php
├─ logout.php
├─ navigation.php
├─ orders.php
├─ page.php
├─ paging.php
├─ place_order.php
├─ product.php
├─ products.php
├─ read_one_order.php
├─ read_products_sorted_by_fields.php
├─ read_products_template.php
├─ register.php
├─ remove_from_cart.php
├─ reset_password.php
├─ search.php
├─ update_quantity.php
├─ navigation.php
├─ verify.php

What People Say

Here are some of the things people say about our source code downloads.

Features List & Download

FEATURE ACCESS LEVEL SOURCE CODE
USER MANAGEMENT
Create user Admin YES
Read users Admin YES
Update user Admin YES
Delete user Admin YES
Search user Admin YES
Users list pagination Admin YES
Valid email format required Admin & Customer YES
Password must be uppercase letter, lowercase letter, number and special character Admin & Customer YES
Confirm password field Admin & Customer YES
Password validation as you type Admin & Customer YES
View customer order history Admin & Customer YES
Deleting first administrator account is not allowed Admin YES
User types: Admin and Customer Admin & Customer YES
Interface for admin Admin YES
Interface for customer Customer YES
Login page Admin & Customer YES
Log out Admin & Customer YES
Sign up page Customer YES
Sign up email notification with validation link Customer YES
Edit profile of currently logged in user Admin & Customer YES
Show name with icon of currently logged in user Admin & Customer YES
Forgot password - system can send unique reset password link via email Customer YES
Forgot password - user can click the unique verification link and reset his password Customer YES
PRODUCT MANAGEMENT
Create product Admin YES
Read products Admin YES
Update product Admin YES
Delete product Admin YES
Search product Admin & Customer YES
Product lists with pagination Admin & Customer YES
View inactive products Admin YES
View products under a category Admin & Customer YES
Product list under a category with pagination Admin & Customer YES
Upload product images, you can select many images at once Admin YES
View product images with thumbnails Admin & Customer YES
Delete product image with X icon Admin YES
Upload product PDFs , you can select many PDF files at once Admin YES
List product PDF Admin YES
Delete product PDF Admin YES
View single product with related information Customer YES
View single product with add to cart button Customer YES
View single product with image slider Customer YES
View single product with SEO friendly URL (.htaccess file used) Customer YES
Rich text editor for product description when adding or editing product Admin YES
Quantity value must be more than 1 Customer YES
Sorting by fields Admin & Customer YES
VARIATION MANAGEMENT
Set variation name Admin YES
Set variation price Admin YES
Set variation stock Admin YES
Stock / inventory decreases when order has been placed Admin YES
Increase stock / inventory by updating the variation Admin YES
Create variation Admin YES
Read list of variation Admin YES
Update variation Admin YES
Delete variation Admin YES
CATEGORY MANAGEMENT
Create category Admin YES
Read categories Admin YES
Update category Admin YES
Delete category Admin YES
Search category Admin YES
Category list with pagination Admin YES
Category search result with pagination Admin YES
View products under a product category Admin & Customer YES
Auto update category drop down in create or update product form Admin Yes
Auto update categories in navigation bar Admin & Customer YES
Highlight selected category in navigation Admin & Customer YES
ORDER MANAGEMENT
Make an order Customer YES
Auto-generated unique transaction ID Customer YES
Add to cart button (for each item) with specified quantity Customer YES
Cart page with list of products added to cart Customer YES
Update quantity button for each item in cart page Customer Yes
Auto-compute subtotal in cart page Customer YES
Auto-compute grand total in cart page Customer YES
Remove from cart button for each item in the cart Customer YES
Empty cart button to remove all items in the cart Customer YES
View order history of a customer Admin & Customer YES
View pending and completed order in separate tabs Admin YES
Checkout page Customer YES
Show billing information on check-out page Customer YES
Edit billing information button on checkout page Customer YES
Show payment information on checkout page Customer YES
Payment via cash on delivery Customer YES
Payment via PayPal Customer YES
Place order page - Thank you message Customer YES
View list of orders Customer YES
Pagination on list of orders Admin & Customer YES
Latest order seen at the top of the list Admin & Customer YES
View details of an order Admin & Customer YES
Auto-compute order totals Admin & Customer YES
Change status of an order (pending or completed) Admin YES
SECURITY
Register user hashed password stored in the database Customer YES
Edit user profile hashed password update in the database Admin YES
Create user hashed password stored in the database Admin YES
Login user with hashed password validation Customer & Admin YES
Used PDO bindParam() to prevent SQL injection in all MySQL queries Developer YES
Used PHP htmlspecialchars() to prevent XSS attacks Developer YES
WEB PAGE MANAGEMENT
Create page Admin YES
Read page Admin YES
Update page Admin YES
Delete page Admin YES
Search page Admin YES
Pages list with pagination Admin YES
Pages search result with pagination Admin YES
CONTACT MANAGEMENT
Send message to Admin Customer YES
Display other ways to contact Admin Customer YES
Display list of messages Admin YES
Messages list with pagination Admin YES
Read message Admin YES
Delete message Admin YES
Search message Admin YES
Messages search result with pagination Admin YES
MORE REASONS TO DOWNLOAD IT
Object oriented programming source code Developer YES
Bootstrap user interface Developer YES
PDO extension used Developer YES
Page title navigation with links Developer YES
Radio button looks like a switch Developer YES
Icon in all create, edit and delete buttons Developer YES
All source code files organized by folders Developer YES
Database configuration file in config folder Developer YES
SQL file and READ-ME.txt that contains login credentials in "sql" folder Developer YES
Well explained / commented source code Developer YES
One-time payment, no recurring payment Developer YES
SUPPORT AND UPDATES
Free support for 1 year. Developer YES
Free source code updates. Developer YES
$250 - Download source code

Simple Set Up

You can run this source code successfully with few easy steps.

10.1 Run the Home Page

I assume you are installing this source code on localhost. In my case, I installed this code in this directory:

The reason for these multiple folders is because I have many projects and I need to organize them this way. I can access the system in this URL: http://localhost/CodeOfaNinja/SourceCodes/Systems/ShoppingCartSystem/

You will see an error, that's why we need to do the following steps.

1. In your PhpMyAdmin, create a database with the name "shopping_cart_system".

2. Import the "shopping_cart_system.sql" SQL file from the "dev" folder.

3. Change rewrite base directory in line 7 of the .htaccess file.

RewriteBase RewriteBase /CodeOfaNinja/SourceCodes/Systems/ShoppingCartSystem/

4. Configure $home_url in line 72 of /config/core.php

$home_url = "http://localhost/CodeOfaNinja/SourceCodes/Systems/ShoppingCartSystem/";

5. Configure database in /config/database.php, example settings would look like:

// specify your own database credentials
private $host = "localhost";
private $db_name = "shopping_cart_system";
private $username = "root";
private $password = "";
public $conn;

6. Try to log in by running the login page.

http://localhost/CodeOfaNinja/SourceCodes/Systems/ShoppingCartSystem/login

Use the following login credentials.

Admin Section Login
Username: [email protected]
Password: [email protected]

Customer Account Login
Username: [email protected]
Password: [email protected]

How To Set Up / Enable Auto Return?

With Auto Return for PayPal Website Payments, your buyers are redirected back to your site immediately after clicking the Pay button on the Payment Confirmation page.

Your buyers enjoy a streamlined checkout experience and are returned back to your site quickly!

1. Enable Auto Return In Your Test / Sandbox Account.

  1. Log into https://developer.paypal.com
  2. Click Applications
  3. Click Sandbox accounts
  4. Expand the account in question
  5. Click Sandbox site
  6. Login to the test account
  7. Copy and paste "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_profile-website-payments" into your browser
  8. Enable Auto Return and click Save
  9. Enter the Auto Return URL and click Save

[Reference]

2. Setting Up Auto Return On Your Official / Real PayPal Account

  1. Log in and click the Profile subtab under My Account.
  2. Click the Website Payment Preferences link under Selling Preferences.
  3. Click the On radio button to enable Auto Return.
  4. Enter the Return URL. Note: You must meet the Return URL requirements in order to set up Auto Return. Learn more about Return URL.

[Reference]

3. How To Disable Sandbox Mode?

This source code is in sandbox mode by default, it means any PayPal transactions are for testing purposes only. To disable the PayPal Sandbox mode:

Open /libs/php/paypal_checkout.php

Change line 51, from

$form='<form id="paypal_checkout" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">';

to

$form='<form id="paypal_checkout" action="https://www.paypal.com/cgi-bin/webscr" method="post">';

Change the email address (line 5) to your real PayPal account email address. Payment will be sent to the specified PayPal account.

How To Make TinyMCE File Manager / File Browser Work?

1. Change line 71 of /libs/js/responsive_filemanager/filemanager/config/config.php

'upload_dir' => '/YOUR_ROOT_DIRECTORY/libs/js/responsive_filemanager/source/',

2. Change line 42-43 of /admin/layout_foot.php

external_filemanager_path:"/YOUR_ROOT_DIRECTORY/libs/js/responsive_filemanager/filemanager/",
external_plugins: { "filemanager" : "/YOUR_ROOT_DIRECTORY/libs/js/responsive_filemanager/filemanager/plugin.min.js"},

Some More Notes

1. This system works with PHP 5.5+

2. Rewrite module must be enable in your apache server (this is enabled by default in most web servers and localhost)

Thanks For Your Help!

YES! The shopping cart system source code is now available! Thanks for all the pre-orders and support! More features and enhancements will be added in the future.

I'll keep you updated via email with the update information and download link. Download the source code by clicking the green BUY button below.

$250 - Download source code

Related Source Codes

Get In Touch

Contact me if you have any questions about the code, I'll be more than happy to help and support you!

My email is [email protected].

Please subscribe as well to receive news and updates about our source codes and free tutorials. Fill out the form below. CLICK HERE TO SUBSCRIBE!

Thank you for visiting our PHP shopping cart source code download page!

PHP Shopping Cart Tutorial – Step By Step Guide!

simple-php-mysql-shopping-cart-tutorial

Previously, we learned how to create, read, update and delete database records on our PHP OOP CRUD tutorial. Today, we will put that knowledge to work by building a simple PHP shopping cart application.

Overview

This is good news for you. If you do not want to use cookies or sessions for storing cart items, you can use your MySQL or MariaDB database.

Will there be any advantage if we use this approach?

One advantage I can think of is, the user can view his cart items in different computers or devices.

If we will compare it to using PHP sessions or cookies, we can say the following:

  • PHP sessions can maintains the cart items only when the browser is opened. It means a user will lose his cart items once he closes his browser or turns off his computer.
  • PHP cookies can maintain the cart items on one device or computer, event if the user turn his computer on and off.

The source codes in this page is NOT for you if:

  • You are an already an expert in PHP & MySQL programming.
  • You have a lot of time to code a shopping cart system from scratch.
  • You are not that interested in learning PHP & MySQL programming.

But, this SOURCE CODE is FOR YOU if:

  • You want to SAVE huge amount of development time.
  • You want to develop your own shopping cart system from scratch.
  • You determined to learn how to make a web application in PHP & MySQL.

But if you are an expert in PHP & MySQL programming and would like to take a look at our code, please do so! We'd love to hear your response and great insights! The comments section below is always open for anyone with questions and suggestions.

Source Code Output Preview

Below are some screenshots of our script’s output. You can click an image to view the larger version of it. Use the left and right arrow to navigate through the screenshots.

Please note that the following images are just output previews. New features might be added already the time you are reading this.

Note: If the output preview is in video format, please click the play button instead.

LEVEL 1 Source Code Output

[espro-slider id=6652]

LEVEL 2 Source Code Output

[espro-slider id=6622]

PHP Shopping Cart Module Output

[espro-slider id=6839]

The LEVEL 2 and PHP Shopping Cart Module outputs proves that you can add and customize more features. It's easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let's proceed to the step by step tutorial of our LEVEL 1 source code. Enjoy!

File Structure

The following folders and files are included in the source code. It will have more meaning if you will see the code inside the folders and files.

├─ config/
├─── database.php
├─ dev/
├─── shop_cart_mysql_1.sql
├─── readme.txt
├─ images/
├─ libs/
├─── css/
├────── bootstrap/
├─── js/
├────── jquery.js
├─ objects/
├─── cart_item.php
├─── product_image.php
├─── product.php
├─ uploads/
├─── images/
├─ .htaccess
├─ add_to_cart.php
├─ cart.php
├─ checkout.php
├─ layout_foot.php
├─ layout_head.php
├─ navigation.php
├─ paging.php
├─ place_order.php
├─ product.php
├─ products.php
├─ read_products_template.php
├─ remove_from_cart.php
├─ update_quantity.php

Prepare the database

Database Design

Our database name is "shop_cart_mysql_1", and we will have three (3) tables.
simple-php-mysql-shopping-cart-tutorial database design

Create MySQL Tables

You may run the following SQL queries on our "shop_cart_mysql_1" database.

Create the products table. This table will hold products record.

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COMMENT='products that can be added to cart' AUTO_INCREMENT=41 ;

Create product_images table. This table will hold images related to product.

CREATE TABLE IF NOT EXISTS `product_images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `name` varchar(512) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='image files related to a product' AUTO_INCREMENT=105 ;

Create cart_items table. This table will hold cart items of our user.

CREATE TABLE IF NOT EXISTS `cart_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `quantity` double NOT NULL,
  `user_id` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=40 ;

The products and product_images table will not fully work without the sample data and images in the "/uploads/images/" directory.

You'll have to download the SQL and image files. Use the download button below. What will you get? A ZIP file with shop_cart_mysql_1.sql and 28 image files inside (1.30 MB).

Once downloaded, you may import the SQL file using PhpMyAdmin. Put the image files in "/uploads/images/" directory. You are now one step closer to the output shown in section 2.1 above.

Database connection file

Create "config" folder and inside it, create "database.php" file with the following code.

<?php
// used to get mysql database connection
class Database{

	// specify your own database credentials
	private $host = "localhost";
	private $db_name = "shop_cart_mysql_1";
	private $username = "root";
	private $password = "";
	public $conn;

	// get the database connection
	public function getConnection(){

		$this->conn = null;

		try{
			$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
		}catch(PDOException $exception){
			echo "Connection error: " . $exception->getMessage();
		}

		return $this->conn;
	}

}
?>

Output

Output screenshots are coming soon!

Prepare the user interface

Layout files are needed so we can use the same header and footer code.

Create header layout file

Create layout_head.php file and place the the following code.

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?></title>

    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

    <!-- custom css for users -->
    <link href="libs/css/user.css" rel="stylesheet" media="screen">

</head>
<body>

	<?php include 'navigation.php'; ?>

    <!-- container -->
    <div class="container">
        <div class="row">

        <div class="col-md-12">
            <div class="page-header">
                <h1><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?></h1>
            </div>
        </div>

5.2 Create footer layout file

Create layout_foot.php file and place the following code.

		</div>
		<!-- /row -->

	</div>
	<!-- /container -->

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- custom script will be here -->

</body>
</html>

Create navigation.php

The "layout_head.php" will not work without the navigation.php file. Create that file and put the following code inside.

<!-- navbar -->
<div class="navbar navbar-default navbar-static-top" role="navigation">
	<div class="container">

		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
			<span class="sr-only">Toggle navigation</span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="products.php">XYZ Webstore</a>
		</div>

		<div class="navbar-collapse collapse">
			<ul class="nav navbar-nav">

				<!-- highlight if $page_title has 'Products' word. -->
				<li <?php echo strpos($page_title, "Product")!==false ? "class='active'" : ""; ?>>
					<a href="products.php">Products</a>
				</li>

				<li <?php echo $page_title=="Cart" ? "class='active'" : ""; ?> >
					<a href="cart.php">
						<!--later, we'll put a PHP code here that will count items in the cart -->
						Cart <span class="badge" id="comparison-count">0</span>
					</a>
				</li>
			</ul>

		</div><!--/.nav-collapse -->

	</div>
</div>
<!-- /navbar -->

Add Custom CSS

Inside "libs/css" directory, create user.css with the following code inside it.

.text-align-center{ text-align:center; }
.f-w-b{ font-weight:bold; }
.display-none{ display:none; }

.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-15-pct{ width:15%; }
.w-20-pct{ width:20%; }
.w-25-pct{ width:25%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-45-pct{ width:45%; }
.w-50-pct{ width:50%; }
.w-55-pct{ width:55%; }
.w-60-pct{ width:60%; }
.w-65-pct{ width:65%; }
.w-70-pct{ width:70%; }
.w-75-pct{ width:75%; }
.w-80-pct{ width:80%; }
.w-85-pct{ width:85%; }
.w-90-pct{ width:90%; }
.w-95-pct{ width:95%; }
.w-100-pct{ width:100%; }

.m-t-0px{ margin-top:0px; }
.m-b-10px{ margin-bottom:10px; }
.m-b-20px{ margin-bottom:20px; }
.m-b-30px{ margin-bottom:30px; }
.m-b-40px{ margin-bottom:40px; }

.stock-text {
    font-weight: bold;
    color: #008a00;
}

.stock-text-red{
    font-weight:bold;
    color:#b12704;
}

.product-detail {
    font-weight: bold;
    margin: 0 0 5px 0;
}

.blueimp-gallery>.prev, .blueimp-gallery>.next{ border:none; }

.update-quantity-form {
    width: 150px;
    float: left;
    margin: 0 10px 0 0;
}

.cart-row {
    border-bottom: thin solid #f1f1f1;
    overflow: hidden;
    width: 100%;
    padding: 20px 0 20px 0;
}

.product-link{
    color:#000000;
}

.product-link:hover{
    color:#000000;
    text-decoration:none;
}

.product-img-thumb {
    margin: 0 0 10px 0;
    width: 100%;
    cursor: pointer;
}

Display Products

Create products.php

Now we are going to start displaying products from the database. Create products.php with the following basic code.

<?php
// set page title
$page_title="Products";

// page header html
include 'layout_head.php';

// contents will be here 

// layout footer code
include 'layout_foot.php';
?>

Include PHP Classes

Put the following code after the opening "php" tag of the previous section.

// connect to database
include 'config/database.php';

// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// connect to database here

Create "product" object file

Create "objects" folder. Inside it, create product.php file with the following code.

<?php
// 'product' object
class Product{

	// database connection and table name
	private $conn;
	private $table_name="products";

	// object properties
	public $id;
	public $name;
	public $price;
	public $description;
	public $category_id;
	public $category_name;
	public $timestamp;

	// constructor
	public function __construct($db){
		$this->conn = $db;
	}
}

Create "product image" object file

Create product_image.php file inside "objects" folder.

<?php
// 'product image' object
class ProductImage{

	// database connection and table name
	private $conn;
	private $table_name = "product_images";

	// object properties
	public $id;
	public $product_id;
	public $name;
	public $timestamp;

	// constructor
	public function __construct($db){
		$this->conn = $db;
	}
}

Create "cart item" object file

Create cart_item.php file inside "objects" folder.

<?php
// 'cart item' object
class CartItem{

    // database connection and table name
    private $conn;
    private $table_name = "cart_items";

    // object properties
    public $id;
    public $product_id;
    public $quantity;
    public $user_id;
    public $created;
    public $modified;

	// constructor
    public function __construct($db){
        $this->conn = $db;
    }
}

Connect to the database

Replace "// connect to database here" comment in products.php file with the following code.

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

Initialize action and pagination

Put the following code after the code on the previous section.

// to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";

// for pagination purposes
$page = isset($_GET['page']) ? $_GET['page'] : 1; // page is the current page, if there's nothing set, default is page 1
$records_per_page = 6; // set records or rows of data per page
$from_record_num = ($records_per_page * $page) - $records_per_page; // calculate for the query LIMIT clause

Request data from the database

Request data from the database. Put the following code after the code on the previous section.

// read all products in the database
$stmt=$product->read($from_record_num, $records_per_page);

// count number of retrieved products
$num = $stmt->rowCount();

// if products retrieved were more than zero
if($num>0){
	// needed for paging
	$page_url="products.php?";
	$total_rows=$product->count();

	// show products
	include_once "read_products_template.php";
}

// tell the user if there's no products in the database
else{
	echo "<div class='col-md-12'>";
    	echo "<div class='alert alert-danger'>No products found.</div>";
	echo "</div>";
}

Add "read" and "count" methods

The previous section will not work without the following code inside "objects/product.php" object file.

// read all products
function read($from_record_num, $records_per_page){

	// select all products query
	$query = "SELECT
				id, name, description, price
			FROM
				" . $this->table_name . "
			ORDER BY
				created DESC
			LIMIT
				?, ?";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );

	// bind limit clause variables
	$stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
	$stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);

	// execute query
	$stmt->execute();

	// return values
	return $stmt;
}

// used for paging products
public function count(){

	// query to count all product records
	$query = "SELECT count(*) FROM " . $this->table_name;

	// prepare query statement
	$stmt = $this->conn->prepare( $query );

	// execute query
	$stmt->execute();

	// get row value
	$rows = $stmt->fetch(PDO::FETCH_NUM);

	// return count
	return $rows[0];
}

Template to display products

The previous section won't work without "read_products_template.php", so create that file and put the following code.

<?php
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	extract($row);

	// creating box
	echo "<div class='col-md-4 m-b-20px'>";

		// product id for javascript access
		echo "<div class='product-id display-none'>{$id}</div>";

		echo "<a href='product.php?id={$id}' class='product-link'>";
			// select and show first product image
			$product_image->product_id=$id;
			$stmt_product_image=$product_image->readFirst();

			while ($row_product_image = $stmt_product_image->fetch(PDO::FETCH_ASSOC)){
				echo "<div class='m-b-10px'>";
					echo "<img src='uploads/images/{$row_product_image['name']}' class='w-100-pct' />";
				echo "</div>";
			}

			// product name
			echo "<div class='product-name m-b-10px'>{$name}</div>";
		echo "</a>";

		// product price and category name
			echo "<div class='m-b-10px'>";
				echo "$" . number_format($price, 2, '.', ',');
			echo "</div>";

			// add to cart button
			echo "<div class='m-b-10px'>";
				// cart item settings
				$cart_item->user_id=1; // we default to a user with ID "1" for now
				$cart_item->product_id=$id;

				// if product was already added in the cart
				if($cart_item->exists()){
					echo "<a href='cart.php' class='btn btn-success w-100-pct'>";
						echo "Update Cart";
					echo "</a>";
				}else{
					echo "<a href='add_to_cart.php?id={$id}&page={$page}' class='btn btn-primary w-100-pct'>Add to Cart</a>";
				}
			echo "</div>";

	echo "</div>";
}

include_once "paging.php";
?>

Add "readFirst()" method

Add "readFirst()" method in "objects/product_image.php" file. The previous section will not work without it.

// read the first product image related to a product
function readFirst(){

	// select query
	$query = "SELECT id, product_id, name
			FROM " . $this->table_name . "
			WHERE product_id = ?
			ORDER BY name DESC
			LIMIT 0, 1";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );

	// sanitize
	$this->id=htmlspecialchars(strip_tags($this->id));

	// bind prodcut id variable
	$stmt->bindParam(1, $this->product_id);

	// execute query
	$stmt->execute();

	// return values
	return $stmt;
}

Add "exists()" method

Open /objects/cart_item.php and add the following method. This method checks if an item is already added to cart or not.

// check if a cart item exists
public function exists(){

    // query to count existing cart item
    $query = "SELECT count(*) FROM " . $this->table_name . " WHERE product_id=:product_id AND user_id=:user_id";

    // prepare query statement
    $stmt = $this->conn->prepare( $query );

    // sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind category id variable
	$stmt->bindParam(":product_id", $this->product_id);
    $stmt->bindParam(":user_id", $this->user_id);

    // execute query
    $stmt->execute();

    // get row value
    $rows = $stmt->fetch(PDO::FETCH_NUM);

    // return
    if($rows[0]>0){
        return true;
    }

    return false;
}

Create pagination file

The previous section won't work without the paging.php file. Create paging.php with the following code.

<?php
echo "<div class='col-md-12'>";

    echo "<ul class='pagination m-b-20px m-t-0px'>";

    // button for first page
    if($page>1){
        echo "<li><a href='{$page_url}' title='Go to the first page.'>";
            echo "First Page";
        echo "</a></li>";
    }

    $total_pages = ceil($total_rows / $records_per_page);

    // range of links to show
    $range = 2;

    // display links to 'range of pages' around 'current page'
    $initial_num = $page - $range;
    $condition_limit_num = ($page + $range)  + 1;

    for ($x=$initial_num; $x<$condition_limit_num; $x++) {

        // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
        if (($x > 0) && ($x <= $total_pages)) {

            // current page
            if ($x == $page) {
                echo "<li class='active'><a href=\"#\">$x <span class=\"sr-only\">(current)</span></a></li>";
            }

            // not current page
            else {
                echo "<li><a href='{$page_url}page=$x'>$x</a></li>";
            }
        }
    }

    // button for last page
    if($page<$total_pages){
        echo "<li>";
            echo "<a href='" . $page_url . "page={$total_pages}' title='Last page is {$total_pages}.'>";
                echo "Last Page";
            echo "</a>";
        echo "</li>";
    }

    echo "</ul>";
echo "</div>";
?>

Output

Output screenshots are coming soon!

How to count items in the cart?

Display count in navigation bar

Open navigation.php and change this line:

<!--later, we'll put a PHP code here that will count items in the cart -->
Cart <span class="badge" id="comparison-count">0</span>

to this:

<a href="cart.php">
	<?php
	// count products in cart
	$cart_item->user_id=1; // default to user with ID "1" for now
	$cart_count=$cart_item->count();
	?>
	Cart <span class="badge" id="comparison-count"><?php echo $cart_count; ?></span>
</a>

Cart item count() method

Open /objects/cart_item.php and put the count() method.

// count user's items in the cart
public function count(){

    // query to count existing cart item
    $query = "SELECT count(*) FROM " . $this->table_name . " WHERE user_id=:user_id";

    // prepare query statement
    $stmt = $this->conn->prepare( $query );

    // sanitize
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

    // bind category id variable
    $stmt->bindParam(":user_id", $this->user_id);

    // execute query
    $stmt->execute();

    // get row value
    $rows = $stmt->fetch(PDO::FETCH_NUM);

    // return
    return $rows[0];
}

Output

Output screenshots are coming soon!

How to add to cart?

Make "add to cart" button work

Put the following code before ending "body" tag of layout_foot.php file.

<script>
$(document).ready(function(){
	// add to cart button listener
	$('.add-to-cart-form').on('submit', function(){

		// info is in the table / single product layout
		var id = $(this).find('.product-id').text();
		var quantity = $(this).find('.cart-quantity').val();

		// redirect to add_to_cart.php, with parameter values to process the request
		window.location.href = "add_to_cart.php?id=" + id + "&quantity=" + quantity;
		return false;
	});
});
</script>

Create add_to_cart.php

Create add_to_cart.php file because when 'Add to cart' button was clicked, that file with the following code inside will be executed.

<?php
// parameters
$product_id = isset($_GET['id']) ? $_GET['id'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : 1;

// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;

// connect to database
include 'config/database.php';

// include object
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// set cart item values
$cart_item->user_id=1; // we default to '1' because we do not have logged in user
$cart_item->product_id=$product_id;
$cart_item->quantity=$quantity;

// check if the item is in the cart, if it is, do not add
if($cart_item->exists()){
	// redirect to product list and tell the user it was added to cart
	header("Location: cart.php?action=exists");
}

// else, add the item to cart
else{
	// add to cart
	if($cart_item->create()){
		// redirect to product list and tell the user it was added to cart
		header("Location: product.php?id={$product_id}&action=added");
	}else{
		header("Location: product.php?id={$product_id}&action=unable_to_add");
	}
}
?>

Put create() method

The previous section will not work without the following code inside our /objects/cart_item.php file.

// create cart item record
function create(){

    // to get times-tamp for 'created' field
    $this->created=date('Y-m-d H:i:s');

    // query to insert cart item record
    $query = "INSERT INTO
                " . $this->table_name . "
            SET
				product_id = :product_id,
				quantity = :quantity,
				user_id = :user_id,
				created = :created";

	// prepare query statement
    $stmt = $this->conn->prepare($query);

	// sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));
	$this->quantity=htmlspecialchars(strip_tags($this->quantity));
	$this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind values
    $stmt->bindParam(":product_id", $this->product_id);
    $stmt->bindParam(":quantity", $this->quantity);
    $stmt->bindParam(":user_id", $this->user_id);
	$stmt->bindParam(":created", $this->created);

	// execute query
    if($stmt->execute()){
        return true;
    }

    return false;
}

Create cart.php

Create cart.php with the following basic code.

<?php
// connect to database
include 'config/database.php';

// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// set page title
$page_title="Cart";

// include page header html
include 'layout_head.php';

// contents will be here 

// layout footer
include 'layout_foot.php';
?>

Display message based on action

We'll display message on cart.php based on given action. Put the following code after "include 'layout_head.php';" of the previous section.

$action = isset($_GET['action']) ? $_GET['action'] : "";

echo "<div class='col-md-12'>";
	if($action=='removed'){
		echo "<div class='alert alert-info'>";
			echo "Product was removed from your cart!";
		echo "</div>";
	}

	else if($action=='quantity_updated'){
		echo "<div class='alert alert-info'>";
			echo "Product quantity was updated!";
		echo "</div>";
	}

	else if($action=='exists'){
		echo "<div class='alert alert-info'>";
			echo "Product already exists in your cart!";
		echo "</div>";
	}

	else if($action=='cart_emptied'){
		echo "<div class='alert alert-info'>";
			echo "Cart was emptied.";
		echo "</div>";
	}

	else if($action=='updated'){
		echo "<div class='alert alert-info'>";
			echo "Quantity was updated.";
		echo "</div>";
	}

	else if($action=='unable_to_update'){
		echo "<div class='alert alert-danger'>";
			echo "Unable to update quantity.";
		echo "</div>";
	}
echo "</div>";

Display cart items

Put the following code based on the code of the previous section.

// $cart_count variable is initialized in navigation.php
if($cart_count>0){

	$cart_item->user_id="1";
	$stmt=$cart_item->read();

	$total=0;
	$item_count=0;

	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);

		$sub_total=$price*$quantity;

		echo "<div class='cart-row'>";
			echo "<div class='col-md-8'>";
				// product name
				echo "<div class='product-name m-b-10px'>";
					echo "<h4>{$name}</h4>";
				echo "</div>";

				// update quantity
				echo "<form class='update-quantity-form'>";
					echo "<div class='product-id' style='display:none;'>{$id}</div>";
					echo "<div class='input-group'>";
						echo "<input type='number' name='quantity' value='{$quantity}' class='form-control cart-quantity' min='1' />";
							echo "<span class='input-group-btn'>";
								echo "<button class='btn btn-default update-quantity' type='submit'>Update</button>";
							echo "</span>";
					echo "</div>";
				echo "</form>";

				// delete from cart
				echo "<a href='remove_from_cart.php?id={$id}' class='btn btn-default'>";
					echo "Delete";
				echo "</a>";
			echo "</div>";

			echo "<div class='col-md-4'>";
				echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
			echo "</div>";
		echo "</div>";

		$item_count += $quantity;
		$total+=$sub_total;
	}

	echo "<div class='col-md-8'></div>";
	echo "<div class='col-md-4'>";
		echo "<div class='cart-row'>";
			echo "<h4 class='m-b-10px'>Total ({$item_count} items)</h4>";
			echo "<h4>$" . number_format($total, 2, '.', ',') . "</h4>";
	        echo "<a href='checkout.php' class='btn btn-success m-b-10px'>";
	        	echo "<span class='glyphicon glyphicon-shopping-cart'></span> Proceed to Checkout";
	        echo "</a>";
		echo "</div>";
	echo "</div>";

}

else{
	echo "<div class='col-md-12'>";
		echo "<div class='alert alert-danger'>";
			echo "No products found in your cart!";
		echo "</div>";
	echo "</div>";
}

8.7 Put read() method in cart item object

Open /objects/cart_item.php and add the following code. The previous section will not work without it. This read() method will query the database and return the products added to the cart.

// read items in the cart
public function read(){

	$query="SELECT p.id, p.name, p.price, ci.quantity, ci.quantity * p.price AS subtotal
			FROM " . $this->table_name . " ci
				LEFT JOIN products p
					ON ci.product_id = p.id
			WHERE ci.user_id=:user_id";

	// prepare query statement
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind value
	$stmt->bindParam(":user_id", $this->user_id, PDO::PARAM_INT);

	// execute query
	$stmt->execute();

	// return values
	return $stmt;
}

Read products by IDs

The previous section will not work without the following "readByIds()" method inside "objects/product.php" file.

// read all product based on product ids included in the $ids variable
// reference http://stackoverflow.com/a/10722827/827418
public function readByIds($ids){

	$ids_arr = str_repeat('?,', count($ids) - 1) . '?';

	// query to select products
	$query = "SELECT id, name, price FROM " . $this->table_name . " WHERE id IN ({$ids_arr}) ORDER BY name";

	// prepare query statement
	$stmt = $this->conn->prepare($query);

	// execute query
	$stmt->execute($ids);

	// return values from database
	return $stmt;
}

Output

Output screenshots are coming soon!

How to update cart?

Update cart quantity with JavaScript

We have the 'update' button on cart.php file. When that button was clicked, a javascript code is triggered. Put the following code inside "$(document).ready(function(){" of layout_foot.php file.

// update quantity button listener
$('.update-quantity-form').on('submit', function(){

	// get basic information for updating the cart
	var id = $(this).find('.product-id').text();
	var quantity = $(this).find('.cart-quantity').val();

	// redirect to update_quantity.php, with parameter values to process the request
	window.location.href = "update_quantity.php?id=" + id + "&quantity=" + quantity;
	return false;
});

PHP script to update cart

The previous section will not work without the update_quantity.php file with the following code inside it.

<?php
// get the product id
$product_id = isset($_GET['id']) ? $_GET['id'] : 1;
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;

// connect to database
include 'config/database.php';

// include object
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// set cart item values
$cart_item->user_id=1; // we default to '1' because we do not have logged in user
$cart_item->product_id=$product_id;
$cart_item->quantity=$quantity;

// add to cart
if($cart_item->update()){
	// redirect to product list and tell the user it was added to cart
	header("Location: cart.php?action=updated");
}else{
	header("Location: cart.php?action=unable_to_update");
}
?>

Update cart item in database

The previous section will not work without the following update() method inside /objects/cart_item.php file.

// create cart item record
function update(){

    // query to insert cart item record
    $query = "UPDATE " . $this->table_name . "
            SET quantity=:quantity
            WHERE product_id=:product_id AND user_id=:user_id";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->quantity=htmlspecialchars(strip_tags($this->quantity));
    $this->product_id=htmlspecialchars(strip_tags($this->product_id));
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

    // bind values
    $stmt->bindParam(":quantity", $this->quantity);
    $stmt->bindParam(":product_id", $this->product_id);
    $stmt->bindParam(":user_id", $this->user_id);

    // execute query
    if($stmt->execute()){
        return true;
    }

    return false;
}

How to remove product from cart?

We have the 'remove' button on cart.php file. When that button was clicked, the remove_from_cart.php file with the following code will be executed.

<?php
// get the product id
$product_id = isset($_GET['id']) ? $_GET['id'] : "";

// connect to database
include 'config/database.php';

// include object
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// remove cart item from database
$cart_item->user_id=1; // we default to '1' because we do not have logged in user
$cart_item->product_id=$product_id;
$cart_item->delete();

// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=removed&id=' . $id);
?>

Put delete() method

The previous section will not work without the following method inside our /objects/cart_item.php file.

// remove cart item by user and product
public function delete(){

	// delete query
	$query = "DELETE FROM " . $this->table_name . " WHERE product_id=:product_id AND user_id=:user_id";
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));
	$this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind ids
	$stmt->bindParam(":product_id", $this->product_id);
	$stmt->bindParam(":user_id", $this->user_id);

	if($stmt->execute()){
		return true;
	}

    return false;
}

Create the checkout page

The checkout page looks like the cart page but the items cannot be updated or removed. It just like the summary of orders. Create checkout.php with the following code.

<?php
// connect to database
include 'config/database.php';

// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// set page title
$page_title="Checkout";

// include page header html
include 'layout_head.php';

// $cart_count variable is initialized in navigation.php
if($cart_count>0){

	$cart_item->user_id="1";
	$stmt=$cart_item->read();

	$total=0;
	$item_count=0;

	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);

		$sub_total=$price*$quantity;

		echo "<div class='cart-row'>";
			echo "<div class='col-md-8'>";

				echo "<div class='product-name m-b-10px'><h4>{$name}</h4></div>";
                echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>{$quantity} item</div>";

			echo "</div>";

			echo "<div class='col-md-4'>";
				echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
			echo "</div>";
		echo "</div>";

		$item_count += $quantity;
		$total+=$sub_total;
	}

	echo "<div class='col-md-12 text-align-center'>";
		echo "<div class='cart-row'>";
            if($item_count>1){
    			echo "<h4 class='m-b-10px'>Total ({$item_count} items)</h4>";
            }else{
                echo "<h4 class='m-b-10px'>Total ({$item_count} item)</h4>";
            }
			echo "<h4>$" . number_format($total, 2, '.', ',') . "</h4>";

	        echo "<a href='place_order.php' class='btn btn-lg btn-success m-b-10px'>";
	        	echo "<span class='glyphicon glyphicon-shopping-cart'></span> Place Order";
	        echo "</a>";
		echo "</div>";
	echo "</div>";

}

else{
	echo "<div class='col-md-12'>";
		echo "<div class='alert alert-danger'>";
			echo "No products found in your cart!";
		echo "</div>";
	echo "</div>";
}

include 'layout_foot.php';
?>

Create place_order.php

We'll use this file to show a "thank you" message and remove all items in the cart.

<?php
// include classes
include_once "config/database.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// remove all cart item by user, from database
$cart_item->user_id=1; // we default to '1' because we do not have logged in user
$cart_item->deleteByUser();

// set page title
$page_title="Thank You!";

// include page header HTML
include_once 'layout_head.php';

echo "<div class='col-md-12'>";
	// tell the user order has been placed
	echo "<div class='alert alert-success'>";
		echo "<strong>Your order has been placed!</strong> Thank you very much!";
	echo "</div>";
echo "</div>";

// include page footer HTML
include_once 'layout_foot.php';

Delete all items in the cart

The previous section will not work without the following method. Open /objects/cart_item.php and put it inside.

// remove cart items by user
public function deleteByUser(){
    // delete query
    $query = "DELETE FROM " . $this->table_name . " WHERE user_id=:user_id";
	$stmt = $this->conn->prepare($query);

	// sanitize
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

    // bind id
    $stmt->bindParam(":user_id", $this->user_id);

	if($stmt->execute()){
		return true;
	}

    return false;
}

Output

Output screenshots are coming soon!

How to make the product page?

Create product.php

Create product.php with the following basic code.

<?php
// include classes
include_once "config/database.php";
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// get ID of the product to be edited
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');
$action = isset($_GET['action']) ? $_GET['action'] : "";

// set the id as product id property
$product->id = $id;

// to read single record product
$product->readOne();

// set page title
$page_title = $product->name;

// include page header HTML
include_once 'layout_head.php';

// content will be here

// include page footer HTML
include_once 'layout_foot.php';
?>

Read product details

Put the following code after "$product_image = new ProductImage($db);" code of the previous section.

// get ID of the product to be edited and action
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');
$action = isset($_GET['action']) ? $_GET['action'] : "";

// set the id as product id property
$product->id = $id;

// to read single record product
$product->readOne();

// set page title
$page_title = $product->name;

Read one product method

The previous section will not work without the "readOne()" method. Add the following method inside "objects/product.php" file.

// used when filling up the update product form
function readOne(){

	// query to select single record
	$query = "SELECT
				name, description, price
			FROM
				" . $this->table_name . "
			WHERE
				id = ?
			LIMIT
				0,1";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );

	// sanitize
	$this->id=htmlspecialchars(strip_tags($this->id));

	// bind product id value
	$stmt->bindParam(1, $this->id);

	// execute query
	$stmt->execute();

	// get row values
	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	// assign retrieved row value to object properties
	$this->name = $row['name'];
	$this->description = $row['description'];
	$this->price = $row['price'];
}

Display message based on action

Open product.php file. Put the following code after ,span class="coan_code">include_once 'layout_head.php'; code.

echo "<div class='col-md-12'>";
	if($action=='added'){
		echo "<div class='alert alert-info'>";
			echo "Product was added to your cart!";
		echo "</div>";
	}

	else if($action=='unable_to_add'){
		echo "<div class='alert alert-info'>";
			echo "Unable to add product to cart. Please contact Admin.";
		echo "</div>";
	}
echo "</div>";

// product thumbnail will be here

Display product thumbnails

When these product thumbnails were hovered, it displayes a larger version of the image. It is Amazon-style.

Open product.php file and replace // product thumbnail will be here comment with the following code.

// set product id
$product_image->product_id=$id;

// read all related product image
$stmt_product_image = $product_image->readByProductId();

// count all relatd product image
$num_product_image = $stmt_product_image->rowCount();

echo "<div class='col-md-1'>";
	// if count is more than zero
	if($num_product_image>0){
		// loop through all product images
		while ($row = $stmt_product_image->fetch(PDO::FETCH_ASSOC)){
			// image name and source url
			$product_image_name = $row['name'];
			$source="uploads/images/{$product_image_name}";
			echo "<img src='{$source}' class='product-img-thumb' data-img-id='{$row['id']}' />";
		}
	}else{ echo "No images."; }
echo "</div>";

Read images related to product

The previous section section will not work without the "readByProductId()" method inside "objects/product_image.php" file.

// read all product image related to a product
function readByProductId(){

	// select query
	$query = "SELECT id, product_id, name
			FROM " . $this->table_name . "
			WHERE product_id = ?
			ORDER BY name ASC";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );

	// sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));

	// bind prodcut id variable
	$stmt->bindParam(1, $this->product_id);

	// execute query
	$stmt->execute();

	// return values
	return $stmt;
}

Display product image

Only one product image are displayed at a time. This part displays the larger product image based on the hovered product thumbnail. Put the following code after the previous section's code.

echo "<div class='col-md-4' id='product-img'>";

	// read all related product image
	$stmt_product_image = $product_image->readByProductId();
	$num_product_image = $stmt_product_image->rowCount();

	// if count is more than zero
	if($num_product_image>0){
		// loop through all product images
		$x=0;
		while ($row = $stmt_product_image->fetch(PDO::FETCH_ASSOC)){
			// image name and source url
			$product_image_name = $row['name'];
			$source="uploads/images/{$product_image_name}";
			$show_product_img=$x==0 ? "display-block" : "display-none";
			echo "<a href='{$source}' target='_blank' id='product-img-{$row['id']}' class='product-img {$show_product_img}'>";
				echo "<img src='{$source}' style='width:100%;' />";
			echo "</a>";
			$x++;
		}
	}else{ echo "No images."; }
echo "</div>";

10.8 Make image hover work

Put the following jQuery code inside "$(document).ready(function(){" of layout_foot.php file.

// change product image on hover
$(document).on('mouseenter', '.product-img-thumb', function(){
	var data_img_id = $(this).attr('data-img-id');
	$('.product-img').hide();
	$('#product-img-'+data_img_id).show();
});

Display product details

This part display product price, description and category. Put the following code after the previous section's code.

echo "<div class='col-md-5'>";

	echo "<div class='product-detail'>Price:</div>";
	echo "<h4 class='m-b-10px price-description'>$" . number_format($product->price, 2, '.', ',') . "</h4>";

	echo "<div class='product-detail'>Product description:</div>";
	echo "<div class='m-b-10px'>";
		// make html
		$page_description = htmlspecialchars_decode(htmlspecialchars_decode($product->description));

		// show to user
		echo $page_description;
	echo "</div>";

	echo "<div class='product-detail'>Product category:</div>";
	echo "<div class='m-b-10px'>{$product->category_name}</div>";

echo "</div>";

Render 'Cart' button

Now we will display 'Add to cart' button if the product is not yet added to cart. Else, we will display 'update cart' button.

Place the following code after the previous section's code.

echo "<div class='col-md-2'>";
	// cart item settings
	$cart_item->user_id=1; // we default to a user with ID "1" for now
	$cart_item->product_id=$id;

	// if product was already added in the cart
	if($cart_item->exists()){
		echo "<div class='m-b-10px'>This product is already in your cart.</div>";
		echo "<a href='cart.php' class='btn btn-success w-100-pct'>";
			echo "Update Cart";
		echo "</a>";
	}

	// if product was not added to the cart yet
	else{

		echo "<form class='add-to-cart-form'>";
			// product id
			echo "<div class='product-id display-none'>{$id}</div>";

			// select quantity
			echo "<div class='m-b-10px f-w-b'>Quantity:</div>";
			echo "<input type='number' class='form-control m-b-10px cart-quantity' value='1' min='1' />";

			// enable add to cart button
			echo "<button style='width:100%;' type='submit' class='btn btn-primary add-to-cart m-b-10px'>";
				echo "<span class='glyphicon glyphicon-shopping-cart'></span> Add to cart";
			echo "</button>";

		echo "</form>";
	}
echo "</div>";

Output

Output screenshots are coming soon!

What People Say About This Code?

I'm so glad that this code delights other people. The following are some of them from the comments section!

★★★★★ "Hey Mike, my name is Leonardo from Argentina. I've been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works... Well, thank you very much man. I really admire your work." ~ Leonardo

★★★★★ "Man, your tut's are awesome. Im so glad ive found your blog. Big respect!" ~ Milos

★★★★★ "I bought your level-2 source code and it was so good, very big help for me. It was worth it. Thank you very much!" ~ Ashley Deanna Plata

★★★★★ "Hello, This is a great script and I have paid 6.99 for your work (it Worth it)." ~ Louis Blais

★★★★★ "Words can't express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!" ~ Jeremy Smith

Download the LEVEL 1 Source Code

You can get the source code by following the whole, well detailed and free tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, orYES
✔ Income you can get from your website project or business.YES
✔ Precious time you save.YES
✔ Expert advice and support (if you have any questions related to the source code)YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

The LEVEL 1 Source code has the following features:

FEATURE LEVEL 1
Learn to code a simple cart function Yes
List all products from MySQL database Yes
Add to cart action button Yes
Remove from cart action button Yes
Show message about a product added to cart Yes
Show message about a product removed from cart Yes
Navigation bar highlights which page is selected Yes
Cart link shows count of products added in the cart Yes
Show message if no products found in database Yes
Show message if no product found in cart Yes
Bootstrap enabled UI Yes
Cart page that lists all products added to cart Yes
Auto-compute total cost of all products added to cart Yes
Specify and save cart quantity Yes
Update cart quantity Yes
PDO extension used Yes
Step by step tutorial Yes
Free code updates Yes
Free support for 6 months Yes
$20 - Download now

Download the LEVEL 2 Source Code

Download the LEVEL 2 Source code, it has more features such as:

FEATURE LEVEL 2
List all products from MySQL database YES
Pagination on products list page YES
Navigation bar has drop down of product categories YES
Highlight selected category in drop down YES
Categories are retrieved from the database YES
Show products by category YES
List products under a category with pagination YES
Search product YES
Search results with pagination YES
Search box located on upper right corner of navigation bar YES
Search box requires search term before clicking the search button YES
Add to cart action button YES
Quantity text box beside the add to cart button YES
Quantity text box required to be a number YES
Quantity text box required to have a minimum value of 1, negative value not allowed YES
Remember the page number where the user clicked the "Add to cart" button YES
Single product view YES
Add to cart text box and button in single product view YES
Quantity text box has up and down arrow for changing value YES
Remove from cart action button YES
Show message about a product added to cart YES
Disable products already added in the cart YES
Show message about a product removed from cart YES
Navigation bar highlights which page is selected YES
Cart link shows count of products added in the cart YES
Show message if no products found in database YES
Show message if no product found in cart YES
Well formatted money value YES
Check out button with cart icon YES
Bootstrap enabled UI YES
Cart page that lists all products added to cart YES
Quantity text box beside update quantity button YES
One click empty cart button YES
Auto-compute total cost of all products added to cart YES
Used PDO bindParam() to prevent SQL injection in MySQL queries YES
Used PHP htmlspecialchars() to prevent XSS attacks YES
SQL file is in the "dev" folder YES
PDO extension used YES
Free code updates YES
Free support for 6 months YES
$40 - Download now

Download the PHP Shopping Cart Module

It has several features you will enjoy learning. Some examples: how to handle the users, shopping cart, and ordering using the PHP & MySQL technology. Click here to learn more or download it now using the button below.

$50 - Download now

Download the "PHP Shopping Cart SYSTEM" Source Code

Many of you requested this source code. You needed a shopping cart system with user management (merchant and customer), product management, category management, order management, security and more features based on our source codes here in codeofaninja.com. Click here to learn more.

What's Next?

We made another version of this tutorial. We used PHP session variables to store cart data. This is a great tutorial about PHP sessions.

You can find the tutorial here: PHP and MySQL Shopping Cart Tutorial – Using SESSIONS To Store Cart Data

Related Tutorials

Please explore more tutorials on our start page. Click here.

Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

Thank you for studying our tutorial about simple PHP MySQL shopping cart tutorial!

How To Display Twitter Feed on Website Using PHP?

Before we start coding, you might be someone NOT interested in coding. If that's the case, you should use a website plugin like SociableKIT. Watch the following video.

Need to embed a Twitter hashtag feed on your website? Watch this tutorial.

What's next? You can try SociableKIT now, view a live demo here and here or continue with the code tutorial below.

Let's code!

Do you actively use Twitter for your brand or products? Does your client use it?

If you use it for your brands or products and you have your own website, it will be a great feature if you can display your twitter feed or posts on your website.

I know, you can embed your Twitter feed using the Twitter widget, but you cannot customize the look and feel.

It looks like the default Twitter interface.

Don't get me wrong, it looks good! But sometimes, our design scheme or our clients have a different requirement, they want the Twitter feed to look different.

The good news is, our code for today is a way to do it!

Source Code Overview

Here’s an overview of what our code does:

  1. It gets a Twitter users's profile information and posts from a specified twitter account. We'll try Taylor Swift's twitter account in the demo.
  2. Display these Twitter data to a webpage (assuming it is your WordPress or PHP website.)
  3. Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here.

Final Output Demo

LEVEL 1 Source Code Output

We have to know where we are going, if we're done with the code tutorial in this post, we will achieve this output:

display-twitter-feed-BASIC

LEVEL 2 Source Code Output

More improvements were provided after the step by step tutorial. If you need more features, you might need the LEVEL 2 version. It has the following output:

display-twitter-feed-pro-katy
display-twitter-feed-pro-ninjazhai

See the full list of features in section 15.0 below. It has all the details of these features.

Obtain Access Tokens and Keys

Go to Twitter Apps page.

Click the 'Create New App' button on the upper right corner.

Fill out the form with your information

Go back to the twitter apps page, you should see your new app now

Click your app and go to the "Keys and Access Tokens" tab

twitter-app-keys

There you will see the access tokens and keys you need:

  • Consumer Key (API Key)
  • Consumer Secret (API Secret)
  • Access Token
  • Access Token Secret

Create The index.php File

We will make index.php Bootstrap ready. For those not familiar with the CSS framework Bootstrap, please refer to our step by step tutorial here:

Step by Step Bootstrap Tutorial for Beginners

The index.php file will have the following code.

<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <title>Display Twitter Feed On Website - LEVEL 2 - Live Demo</title>
 
        <!-- Bootstrap CSS -->
    <link href="libs/js/bootstrap/dist/css/bootstrap.css" rel="stylesheet" media="screen">
</head>
<body>
 
<!-- PAGE CONTENT and PHP CODE WILL BE HERE -->
 
<!-- jQuery library -->
<script src="libs/js/jquery.js"></script>
 
<!-- bootstrap JavaScript -->
<script src="libs/js/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/js/bootstrap/docs-assets/js/holder.js"></script>
 
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
 
</body>
</html>

Put Container Tags, Page Title and HTML

We will have the following code inside the "body" tag of our code in section 4.0

<div class="container">
 
    <div class="col-lg-12">
        <div class="page-header">
            <h1>Display Twitter Feed On Website - LEVEL 1 - Live Demo</h1>
        </div>
    </div>
 
    <div class="col-lg-4">
        <!-- TWITTER USER PROFILE INFORMATION WILL BE HERE -->
    </div> <!-- end <div class="col-lg-4"> -->
 
    <div class="col-lg-8">
        <!-- TWITTER USER FEED WILL BE HERE -->
    </div> <!-- end <div class="col-lg-8"> -->
 
</div> <!-- end <div class="container"> -->

Specify Keys And Variable Values

The following code will be inside the DIV tag with class="col-lg-4".

Access token and keys value were retrieved during our section 3.0 earlier.

<?php
// keys from your app
$oauth_access_token = "change_to_your_oauth_access_token ";
$oauth_access_token_secret = "change_to_your_oauth_access_token_secret ";
$consumer_key = "change_to_your_consumer_key ";
$consumer_secret = "change_to_your_consumer_secret ";
 
// we are going to use "user_timeline"
$twitter_timeline = "user_timeline";
 
// specify number of tweets to be shown and twitter username
// for example, we want to show 20 of Taylor Swift's twitter posts
$request = array(
    'count' => '10',
    'screen_name' => 'taylorswift13'
);
?>

Get OAuth Signature

OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. More about Twitter OAuth here.

Put the following code below our code on section 6.0

// put oauth values in one oauth array variable
$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_nonce' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_token' => $oauth_access_token,
    'oauth_timestamp' => time(),
    'oauth_version' => '1.0'
);
 
// combine request and oauth in one array
$oauth = array_merge($oauth, $request);
 
// make base string
$baseURI="https://api.twitter.com/1.1/statuses/$twitter_timeline.json";
$method="GET";
$params=$oauth;
 
$r = array();
ksort($params);
foreach($params as $key=>$value){
    $r[] = "$key=" . rawurlencode($value);
}
$base_info = $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
 
// get oauth signature
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

Make The Authorization Request

We can now make request to the Twitter API with the help of $oauth variable and cURL.

Put the follwing code below our code on section 7.0

// make request
// make auth header
$r = 'Authorization: OAuth ';
 
$values = array();
foreach($oauth as $key=>$value){
    $values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$r .= implode(', ', $values);
 
// get auth header
$header = array($r, 'Expect:');
 
// set cURL options
$options = array(
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_HEADER => false,
    CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => true
);

Retrieve Twitter Feeds With User Information

Using the the following code, we can get the data in JSON format. Put it below our code on section 8.0

// retrieve the twitter feed
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
 
// decode json format tweets
$tweets=json_decode($json, true);

Display Twitter User Information

The following code shows how we can display the specified Twitter user's information. Put it below our code on section 9.0

// show user information
echo "<div class='overflow-hidden'>";
 
    // user data
    $profile_photo=str_replace("normal", "400x400", $tweets[0]['user']['profile_image_url_https']);
    $name=$tweets[0]['user']['name'];
    $screen_name=$tweets[0]['user']['screen_name'];
 
    // show profile photo
    echo "<img src='{$profile_photo}' class='img-thumbnail' />";
 
    // show other information about the user
    echo "<div class='text-align-center'>";
        echo "<div><h2>{$name}</h2></div>";
        echo "<div><a href='https://twitter.com/{$screen_name}' target='_blank'>@{$screen_name}</a></div>";
    echo "</div>";
 
    echo "<hr />";
echo "</div>";

Display Twitter User Status Count And Follower Count

Now we will put the following code inside the DIV tag with class="col-lg-8".

<?php
$statuses_count=$tweets[0]['user']['statuses_count'];
$followers_count=$tweets[0]['user']['followers_count'];
 
// show numbers
echo "<div class='overflow-hidden'>";
 
    // show number of tweets
    echo "<div class='float-left margin-right-2em text-align-center'>";
        echo "<div class='color-gray'>Tweets</div>";
        echo "<div class='badge font-size-20px'>" . number_format($statuses_count, 0, '.', ',') . "</div>";
    echo "</div>";
 
    // show number of followers
    echo "<div class='float-left margin-right-2em text-align-center'>";
        echo "<div class='color-gray'>Followers</div>";
        echo "<div class='badge font-size-20px'>" . number_format($followers_count, 0, '.', ',') . "</div>";
    echo "</div>";
 
echo "</div>";
 
echo "<hr />";
?>

Display Twitter Posts / Status Feed

Finally we can now display the user's Twitter posts.

// show tweets
foreach($tweets as $tweet){
 
    // show a tweet
    echo "<div class='overflow-hidden'>";
 
        // show picture
        echo "<div class='tweet-image'>";
            echo "<img src='{$profile_photo}' class='img-thumbnail' />";
        echo "</div>";
 
        // show tweet content
        echo "<div class='tweet-text'>";
 
            // show name and screen name
            echo "<h4 class='margin-top-4px'>";
                echo "<a href='https://twitter.com/{$screen_name}'>{$name}</a> ";
                echo "<span class='color-gray'>@{$screen_name}</span>";
            echo "</h4>";
 
            // show tweet text
            echo "<div class='margin-zero'>";
 
                // get tweet text
                $tweet_text=$tweet['text'];
 
                // make links clickable
                $tweet_text=preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $tweet_text);
 
                // output
                echo $tweet_text;
            echo "</div>";
        echo "</div>";
 
    echo "</div>";
    echo "<hr />";
}

Add Your Custom Styling

The following CSS code is what I used to add a some style on our page. I put it inside the "head" tag, just below the Bootstrap CSS.

<!-- custom CSS -->
<style>
.overflow-hidden{
    overflow:hidden;
}
 
.left-margin-10px{
    margin:0 1em 0 0;
}
 
.margin-right-1em{
    margin-right:1em;
}
 
.margin-right-2em{
    margin-right:2em;
}
 
.text-align-center{
    text-align:center;
}
 
.margin-top-4px{
    margin-top:4px;
}
 
.color-gray{
    color:#999;
}
 
.tweet-image{
    float:left; width:15%;
    margin-right:1em;
}
 
.tweet-image img{
    width:100%;
}
 
.tweet-text{
    float:left; width:80%;
}
 
.margin-zero{
    margin:0;
}
 
.font-size-20px{
    font-size:20px;
}
 
.float-left{
    float:left;
}
</style>

Control Background and Link Colors

You can control or change the background or link colors by going to the design settings section of your twitter account.

Here's how you can go to that page:

  1. Go to twitter.com.
  2. On the upper right corner of the page, click your picture.
  3. Click "Settings" in the dropdown.
  4. On the left side bar, click "Design".

You should see the following page.

display-twitter-feed-pro-design-settings

"Theme Color" is the link color. Changes made here will reflect in your page using the LEVEL 2 source code.

Download The Source Code

Getting The Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, orYES
✔ Income you can get from your website project or business.YES
✔ Precious time you save.YES
✔ Expert advice you can get from me, just in case you have any questions with the code.YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

Download the LEVEL 1 Source Code

FEATURES LEVEL 1
Show Twitter users' profile picture YES
Show Twitter users' name YES
Show Twitter users' username with link YES
Show number of tweets YES
Show exact number of followers YES
Specify number of tweets to display YES
Specify Twitter username where to get tweets YES
Show profile pic in tweets YES
Show profile name in tweets YES
Show profile username in tweets YES
Show original tweets YES
Show retweets YES
Links in tweets are clickable YES
Bootstrap enabled YES
Mobile friendly YES
Download Now

Download LEVEL 2 Source Code

FEATURES LEVEL 2
All features of the LEVEL 1 version YES
Show twitter profile description YES
Show twitter user's website with link YES
Show number of following YES
Show number of favorites YES
Twitter profile mentions in tweets are clickable YES
Show when a tweet was tweeted with "Time ago" format YES
Show profile banner image YES
Apply background color set in design settings YES
Apply link color set in design settings YES
Free email support for 6 months. Yes
Free source code updates. Yes
Download Now

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use on unlimited number of websites and Twitter accounts! YES
No different kind of licenses. YES
No many different pricing schemes. YES
No monthly or any recurring fees. YES
No need to rely on another website to render Twitter feed. YES
No need for codes from other websites. YES
You can learn more how to code, I love teaching and can give you free tips! YES
Familiarize yourself with the Twitter API. YES
Features are constantly improving, and you get it for free. YES
Completely customizable. YES

Thank you for supporting our projects here at codeofaninja.com!

Do You Want a Demo?

If you want a demo to see if this will work with your own Twitter account, please send me a message via email [email protected], or via our official Facebook page!

Please provide your Twitter username on the message, thanks!

Social Media Scripts – LEVEL 3 – PRO PACK

Social Media Scripts - LEVEL 3 - PRO PACK
ITEM Original Cost LEVEL 3 PRO PACK
Display Facebook EVENTS on Website $49.99 YES
Display Facebook PHOTOS on Website $49.99 YES
Display Facebook VIDEOS on Website $49.99 YES
Display Facebook FEED on Website $49.99 YES
Display Instagram FEED On Your Website $49.99 YES
BONUS! The following script does not have LEVEL 3, only LEVEL 2. We will give them to you as bonus.
Display Twitter FEED on Website $29.99 YES
Display Google+ FEED on Website $29.99 YES
BUY TO DOWNLOAD PRO PACK NOW FOR ONLY $309.93 $198
Read more about this package.

What's Next?

Today we have learned how to show a Twitter Feed on your website.

Did you know that you can display Google+ Feed on your website as well?

Let us go to the next tutorial: How To Display Google+ Feed on Website?

Related Source Codes

Did you know that you can also display other social media data on your website? I’ve created tutorials on them too, see the following:

Social Media Script Tutorials
Display Facebook Page EVENTS on Website
Display Facebook Page PHOTOS on Website
Display Facebook Page VIDEOS on Website
Display Facebook Page POSTS on Website
Display Instagram FEED On Your Website
Display Twitter FEED on Website
Display Google+ FEED on Website

Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email [email protected], or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

  • 1. Subscribe to social media scripts tutorial news and updates.
  • 2. Be updated about what works and what does not work on social media APIs.
  • 3. Be notified for any related social media API updates.
100% Privacy. We will never spam you!

#3 Thank You!

Thanks for visiting our tutorial on how to display twitter feed on website using PHP!

AJAX CRUD Tutorial Using JavaScript, JSON, and PHP – Step by Step Guide!


Previously, we learned how to create a simple REST API in PHP. Today, we are going to learn how to create or insert, read, update and delete records with our AJAX CRUD Tutorial. We will use JavaScript, JSON, and PHP.

Overview

What Is AJAX? It stands for "Asynchronous JavaScript and XML".

I’ll try to explain it in the simplest way: Using AJAX will prevent re-loading the whole page for every button click you make. As a result, it makes the user experience better. Your web app will be faster.

Ajax is not a technology, but a group of technologies. This can include HTML, CSS, JavaScript, and server-side scripting like PHP.

I highly recommend studying the previous tutorials first before proceeding here. But if you think you can take this one, then go on.

This tutorial will focus on creating, reading, updating, and deleting database records. We will do it using JavaScript, JSON, and PHP.

jQuery will help us with the AJAX part. JSON data will be handled by the REST API built using PHP.

Program Output - PHP AJAX CRUD Tutorial

Below are the screenshots of our tutorial's final result. You can click an image to view the larger version of it.

Create a record.
Read list of records.
Read one record.
When delete button was clicked.

Let’s proceed to the step-by-step tutorial of our LEVEL 1 source code. Enjoy!

Set Up The REST API

In this tutorial, we are going to use a REST API built with PHP.

We did not include REST API source code because we want you to focus on learning how to code with AJAX, not PHP.

But the good news is, we made a separate tutorial about how to build a simple REST API with PHP. Click here to learn the step-by-step PHP REST API tutorial.

I highly recommend learning our REST API tutorial first. This is because we are going to use that API for the rest of this tutorial.

But if you already have your own REST API that will work with this tutorial, that's okay as well.

In my case, one example where I can access the REST API is: http://localhost/api/product/read.php

That link will show me the list of products from the database, in JSON format. It looks like the following screenshot.

The data above will be consumed by our AJAX app. The list of products will be displayed in the Bootstrap table with buttons like "Read One", "Update" and "Delete". You will see it in the "How To Read JSON Data Using jQuery AJAX?" section of this tutorial.

By the way, I'm using a Chrome extension called JSONView to make the JSON data readable in the browser.

Basic Files & Folders

File Structure

We will have the following files and folders at the end of this LEVEL 1 source code tutorial.

├─ app/
├─── assets/
├────── css/
├───────── style.css
├────── js/
├───────── bootbox.min.js
├───────── jquery.js
├─── products/
├────── create-product.js
├────── delete-product.js
├────── read-one-product.js
├────── read-products.js
├────── update-product.js
├─── app.js
├─ index.html

On the next sections, we will start creating the files and folders to achieve the one above.

Create index.html file

Create index.html file on your project's main folder. Open that file and put the following code.

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Read Products</title>

    <!-- bootstrap CSS -->
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<!-- custom CSS -->
	<link href="app/assets/css/style.css" rel="stylesheet" />

</head>
<body>

<!-- our app will be injected here -->
<div id="app"></div>

<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
    </script>

<!-- bootbox for confirm pop up -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>

<!-- app js script -->
<script src="app/app.js"></script>

<!-- products scripts -->
<script src="app/products/read-products.js"></script>
<script src="app/products/create-product.js"></script>
<script src="app/products/read-one-product.js"></script>
<script src="app/products/update-product.js"></script>
<script src="app/products/delete-product.js"></script>

</body>
</html>

Create custom CSS file

  1. Create "app" folder.
  2. Open the "app" folder and create the "assets" folder.
  3. Open the "assets" folder and create the "css" folder.
  4. Open the "css" folder and create "style.css" file.

The "style.css" file is our custom CSS file. You can put any CSS in this file for additional web page styling. In our case, we have the following CSS code inside the "style.css" file.

.m-r-10px{ margin-right:10px; }
.m-b-10px{ margin-bottom:10px; }
.m-b-15px{ margin-bottom:15px; }
.m-b-20px{ margin-bottom:20px; }
.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-15-pct{ width:15%; }
.w-20-pct{ width:20%; }
.w-25-pct{ width:25%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-45-pct{ width:45%; }
.w-50-pct{ width:50%; }
.w-55-pct{ width:55%; }
.w-60-pct{ width:60%; }
.w-65-pct{ width:65%; }
.w-70-pct{ width:70%; }
.w-75-pct{ width:75%; }
.w-80-pct{ width:80%; }
.w-85-pct{ width:85%; }
.w-90-pct{ width:90%; }
.w-95-pct{ width:95%; }
.w-100-pct{ width:100%; }
.display-none{ display:none; }
.padding-bottom-2em{ padding-bottom:2em; }
.width-30-pct{ width:30%; }
.width-40-pct{ width:40%; }
.overflow-hidden{ overflow:hidden; }
.margin-right-1em{ margin-right:1em; }
.right-margin{ margin:0 .5em 0 0; }
.margin-bottom-1em { margin-bottom:1em; }
.margin-zero{ margin:0; }
.text-align-center{ text-align:center; }

Use jQuery, Bootstrap, and Bootbox.js libraries

As you can see in the index.html file, we are using jQuery and Bootbox.js libraries.

jQuery JavaScript library is needed to make it easy for us to control interactions like button click and form submission. In this tutorial, we are using jQuery version 3.6.0. jQuery CDN is here.

Bootstrap makes it easy for us to have a good-looking user interface. We are using Bootstrap version 3.3.7 in this tutorial. Bootstrap CDN is here.

Bootbox.js library is needed to make the "delete" confirmation dialog box look better. We are using Bootbox.js version 4.4.0 in this tutorial. Bootbox.js CDN is here.

Create app.js file

The "app.js" file contains some basic HTML and JavaScript functions that can be used by other JS files in our app.

  1. Open "app" folder.
  2. Inside that "app" folder, create "app.js" file.
  3. Open "app.js" file and put the following code.
$(document).ready(function(){

    // app html
    var app_html=`
        <div class='container'>

            <div class='page-header'>
                <h1 id='page-title'>Read Products</h1>
            </div>

            <!-- this is where the contents will be shown. -->
            <div id='page-content'></div>

        </div>`;

    // inject to 'app' in index.html
    $("#app").html(app_html);

});

// change page title
function changePageTitle(page_title){

	// change page title
	$('#page-title').text(page_title);

	// change title tag
	document.title=page_title;
}

// function to make form values to json format
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Create "products" scripts

Now, we will create several JavaScript files.

  1. Open "app" folder.
  2. Create "products" folder inside "app" folder.
  3. Create the following files inside "products" folder:
    • read-products.js
    • create-product.js
    • read-one-product.js
    • update-product.js
    • delete-product.js

What's the code inside the JavaScript files above? For now, we will leave them empty. But we will fill them out in the next several sections of this tutorial.

Output

Our code so far will have almost empty output. It should look like the following.

How To Read JSON Data Using jQuery AJAX?

Show products on first page load

  1. Open "app" folder.
  2. Open "products" folder inside the "app" folder.
  3. Open read-products.js file inside the "products" folder.

The following code will call the showProducts() method on first load of the web page.

The showProducts() will show the list of products in an HTML table. Put the following code inside read-products.js file.

$(document).ready(function(){

    // show list of product on first load
    showProducts();

});

// showProducts() method will be here

Show products on click of a button

The following code will call showProducts() method in a click of a button with read-products-button class.

The button can be found in the "create product" and "update product" HTML template. We will see it in the next sections.

Put the following code under the showProducts(); of the previous section.

// when a 'read products' button was clicked
$(document).on('click', '.read-products-button', function(){
	showProducts();
});

Create showProducts() function

Now we will create the showProducts() method. Replace // showProducts() method will be here comment in read-products.js file with the following code.

// function to show list of products
function showProducts(){

}

Get list of products

The following code will contact our API to get the list of products in JSON format. Put the following code after the opening curly brace of the previous section.

// get list of products from the API
$.getJSON("http://localhost/api/product/read.php", function(data){

});

Add "Create Product" button

We have to add a "Create Product" button in the "products list" view. We will make this button work later in this tutorial.

Place the following code after the opening curly brace of the previous section.

// html for listing products
var read_products_html=`
    <!-- when clicked, it will load the create product form -->
    <div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>
        <span class='glyphicon glyphicon-plus'></span> Create Product
    </div>

Build HTML table

We have to start building the HTML table where the list of products will appear.

The following code will build an HTML table with its heading. Place it after the previous section's code.

<!-- start table -->
<table class='table table-bordered table-hover'>

    <!-- creating our table heading -->
    <tr>
        <th class='w-25-pct'>Name</th>
        <th class='w-10-pct'>Price</th>
        <th class='w-15-pct'>Category</th>
        <th class='w-25-pct text-align-center'>Action</th>
    </tr>`;

	// rows will be here

// end table
read_products_html+=`</table>`;

Build table row per record

We will loop through each record returned by the API. In each record, we will create a table row.

Aside from product data, the table row will have the "action" buttons as well. These include the "Read One", "Edit" and "Delete" buttons.

Replace "// rows will be here" comment of the previous section with the following code.

// loop through returned list of data
$.each(data.records, function(key, val) {

    // creating new table row per record
    read_products_html+=`
        <tr>

            <td>` + val.name + `</td>
            <td>$` + val.price + `</td>
            <td>` + val.category_name + `</td>

            <!-- 'action' buttons -->
            <td>
                <!-- read product button -->
                <button class='btn btn-primary m-r-10px read-one-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-eye-open'></span> Read
                </button>

                <!-- edit button -->
                <button class='btn btn-info m-r-10px update-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-edit'></span> Edit
                </button>

                <!-- delete button -->
                <button class='btn btn-danger delete-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-remove'></span> Delete
                </button>
            </td>

        </tr>`;
});

Inject to page content

We have to make the HTML table appear on our webpage. We will do this by injecting the table into the "page-content" div.

Place the following code after the closing "table" tag

// inject to 'page-content' of our app
$("#page-content").html(read_products_html);

5.9 Change page title

The following code will change the "title" seen on the web page and the "title" seen on the browser tab.

Place the following code after the previous section's code.

// chage page title
changePageTitle("Read Products");

Output

After doing all the steps above, the output should look like the following.

How To Create or Insert Data Using jQuery AJAX?

Handle "Create Product" Button Click

  1. Open "app" folder.
  2. Open "products" folder inside the "app" folder.
  3. Open create-product.js file inside the "products" folder.

The following code will handle a click of a button. This button should have "create-product-button" class.

Place the following code inside create-product.js file.

$(document).ready(function(){

    // show html form when 'create product' button was clicked
    $(document).on('click', '.create-product-button', function(){
		// categories api call will be here
    });

	// 'create product form' handle will be here
});

Get list of categories from API

We need to get list of categories from the API because we will build the "categories" select field. This is where the user can select the category of the product.

Replace "// categories api call will be here" of the previous section with the following code.

// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){

});

Build "categories option" select field

This is where we build the HTML "select" field with the "categories" option.

Place the following code after the opening curly brace of the previous section.

// build categories option html
// loop through returned list of data
var categories_options_html=`<select name='category_id' class='form-control'>`;
$.each(data.records, function(key, val){
    categories_options_html+=`<option value='` + val.id + `'>` + val.name + `</option>`;
});
categories_options_html+=`</select>`;

Add "Read Products" button

The "read products" button is needed so that we can go back to the products list.

Place the following code after the previous section's code.

// we have our html form here where product information will be entered
// we used the 'required' html5 property to prevent empty fields
var create_product_html=`

    <!-- 'read products' button to show list of products -->
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>

Build "Create Product" HTML Form

Now we will build the actual "creat product" HTML form. This is where the user can enter the new product information that will be sent to the server.

Place the following code after the previous section's code.

<!-- 'create product' html form -->
<form id='create-product-form' action='#' method='post' border='0'>
    <table class='table table-hover table-responsive table-bordered'>

        <!-- name field -->
        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' required /></td>
        </tr>

        <!-- price field -->
        <tr>
            <td>Price</td>
            <td><input type='number' min='1' name='price' class='form-control' required /></td>
        </tr>

        <!-- description field -->
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control' required></textarea></td>
        </tr>

        <!-- categories 'select' field -->
        <tr>
            <td>Category</td>
            <td>` + categories_options_html + `</td>
        </tr>

        <!-- button to submit form -->
        <tr>
            <td></td>
            <td>
                <button type='submit' class='btn btn-primary'>
                    <span class='glyphicon glyphicon-plus'></span> Create Product
                </button>
            </td>
        </tr>

    </table>
</form>`;

Show "Create Product" form and change page title

We have to make the HTML button and form appear on our web page. We will change the page title as well.

Place the following code after the previous section's code.

// inject html to 'page-content' of our app
$("#page-content").html(create_product_html);

// chage page title
changePageTitle("Create Product");

Handle "create product" form submit

If the "create product" form is submitted, we need a script to handle it.

Find "// 'create product form' handle will be here" and replace it with the following code.

// will run if create product form was submitted
$(document).on('submit', '#create-product-form', function(){
	// form data will be here
});

Get form data

This is how we get data entered in our "create product" HTML form.

Replace "// form data will be here" of the previous section with the following code.

// get form data
var form_data=JSON.stringify($(this).serializeObject());

Now we will send the data to the server.

Place the following code after the previous section's code.

// submit form data to api
$.ajax({
	url: "http://localhost/api/product/create.php",
	type : "POST",
	contentType : 'application/json',
	data : form_data,
	success : function(result) {
		// product was created, go back to products list
		showProducts();
	},
	error: function(xhr, resp, text) {
		// show error to console
		console.log(xhr, resp, text);
	}
});

return false;

Output

The output should look like the following.

How To Read One Data Using jQuery AJAX?

Handle "read one" button click

The "read one" button is seen on the "product list" view. When click, it should show the complete product details.

  1. Open "app" folder.
  2. Inside the "app" folder, open "products" folder.
  3. Inside the "products" folder, open "read-one-product.js" file.

Place the following code inside "read-one-product.js" file.

$(document).ready(function(){

    // handle 'read one' button click
    $(document).on('click', '.read-one-product-button', function(){
		// product ID will be here
    });

});

Get product ID

Our script need to identify the record to be read. We do it by getting the product ID.

Replace "// product ID will be here" of the previous section with the following code.

// get product id
var id = $(this).attr('data-id');

Read one record from API

We will send the product ID to the API. It will return the data based on the given ID.

Place the following code after the previous section's code.

// read product record based on given ID
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){
	// read products button will be here
});

Add "read products" button

We need the "read products" button so we can go back to the products list.

Replace "// read products button will be here" of the previous section with the following code.

// start html
var read_one_product_html=`

    <!-- when clicked, it will show the product's list -->
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>

Show record data in HTML table

We will place the product information returned by the API to an HTML table.

Place the following code after the previous section's code.

<!-- product data will be shown in this table -->
<table class='table table-bordered table-hover'>

    <!-- product name -->
    <tr>
        <td class='w-30-pct'>Name</td>
        <td class='w-70-pct'>` + data.name + `</td>
    </tr>

    <!-- product price -->
    <tr>
        <td>Price</td>
        <td>` + data.price + `</td>
    </tr>

    <!-- product description -->
    <tr>
        <td>Description</td>
        <td>` + data.description + `</td>
    </tr>

    <!-- product category name -->
    <tr>
        <td>Category</td>
        <td>` + data.category_name + `</td>
    </tr>

</table>`;

Show "Read One Product" HTML table and change page title

We have to make the HTML button and table appear on our web page. We will change the page title as well.

Place the following code after the previous section's code.

// inject html to 'page-content' of our app
$("#page-content").html(read_one_product_html);

// chage page title
changePageTitle("Create Product");

Output

The output should look like the following.

How To Update Data Using jQuery AJAX?

Handle "udpate product" button click

The "edit" button is seen on the "product list" view. When click, it should show the "update product" form filled out with product information.

  1. Open "app" folder.
  2. Inside the "app" folder, open "products" folder.
  3. Inside the "products" folder, open "update-product.js" file.

Place the following code inside "update-product.js" file.

$(document).ready(function(){

    // show html form when 'update product' button was clicked
    $(document).on('click', '.update-product-button', function(){
		// product ID will be here
    });

	// 'update product form' submit handle will be here
});

8.2 Get product ID

Our script need to identify the record to be read. We do it by getting the product ID.

Replace "// product ID will be here" of the previous section with the following code.

// get product id
var id = $(this).attr('data-id');

Read product information

To fill out our "update product" HTML form, we need to get product information from the API.

Place the following code after the previous section's code.

// read one record based on given product id
$.getJSON("http://localhost/api/product/read_one.php?id=" + id, function(data){

	// values will be used to fill out our form
	var name = data.name;
	var price = data.price;
	var description = data.description;
	var category_id = data.category_id;
	var category_name = data.category_name;

	// load list of categories will be here
});

Get list of categories

A list of categories is needed for product category options. Category records will be rendered as options in a "select" HTML input field.

Replace "// load list of categories will be here" of the previous section with the following code.

// load list of categories
$.getJSON("http://localhost/api/category/read.php", function(data){

	// build 'categories option' html
	// loop through returned list of data
        var categories_options_html=`<select name='category_id' class='form-control'>`;

        $.each(data.records, function(key, val){
            // pre-select option is category id is the same
            if(val.id==category_id){ categories_options_html+=`<option value='` + val.id + `' selected>` + val.name + `</option>`; }

            else{ categories_options_html+=`<option value='` + val.id + `'>` + val.name + `</option>`; }
        });
        categories_options_html+=`</select>`;

	// update product html will be here
});

Add "Read Products" button

The "read products" button is needed so that we can go back to the products list.

Replace "// update product html will be here" of the previous section with the following code.

// store 'update product' html to this variable
var update_product_html=`
    <div id='read-products' class='btn btn-primary pull-right m-b-15px read-products-button'>
        <span class='glyphicon glyphicon-list'></span> Read Products
    </div>

Build "Update Product" form

Now we will build the "update product" HTML form. This form will be built with an HTML table and the input fields are filled out with product information.

Place the following code after the previous section's code.

<!-- build 'update product' html form -->
<!-- we used the 'required' html5 property to prevent empty fields -->
<form id='update-product-form' action='#' method='post' border='0'>
    <table class='table table-hover table-responsive table-bordered'>

        <!-- name field -->
        <tr>
            <td>Name</td>
            <td><input value=\"` + name + `\" type='text' name='name' class='form-control' required /></td>
        </tr>

        <!-- price field -->
        <tr>
            <td>Price</td>
            <td><input value=\"` + price + `\" type='number' min='1' name='price' class='form-control' required /></td>
        </tr>

        <!-- description field -->
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control' required>` + description + `</textarea></td>
        </tr>

        <!-- categories 'select' field -->
        <tr>
            <td>Category</td>
            <td>` + categories_options_html + `</td>
        </tr>

        <tr>

            <!-- hidden 'product id' to identify which record to delete -->
            <td><input value=\"` + id + `\" name='id' type='hidden' /></td>

            <!-- button to submit form -->
            <td>
                <button type='submit' class='btn btn-info'>
                    <span class='glyphicon glyphicon-edit'></span> Update Product
                </button>
            </td>

        </tr>

    </table>
</form>`;

Show "Update Product" form and change page title

We need to show our "update product" HTML on our webpage. We will change the page title as well.

Put the following code after the previous section's code.

// inject to 'page-content' of our app
$("#page-content").html(update_product_html);

// chage page title
changePageTitle("Update Product");

Handle "udpate product" form submission

If the "update product" form is submitted, we need a script to handle it.

Find "// 'update product form' submit handle will be here" and replace it with the following code.

// will run if 'create product' form was submitted
$(document).on('submit', '#update-product-form', function(){

	// get form data will be here 

	return false;
});

Get form data

We will get the product information from our "update product" HTML form.

Replace "// get form data will be here" of the previous section with the following code.

// get form data
var form_data=JSON.stringify($(this).serializeObject());

Send form data to server

After getting the form data, we will send the data to our API.

Place the following code after the previous section's code.

// submit form data to api
$.ajax({
	url: "http://localhost/api/product/update.php",
	type : "POST",
	contentType : 'application/json',
	data : form_data,
	success : function(result) {
		// product was created, go back to products list
		showProducts();
	},
	error: function(xhr, resp, text) {
		// show error to console
		console.log(xhr, resp, text);
	}
});

Output

The output should look like the following.

How To Delete Data Using AJAX?

Handle "Delete Product" button click

The "delete product" button is seen in the "read products" view. When it was clicked, we need to handle it.

  1. Open "app" folder.
  2. Inside the "app" folder, open "products" folder.
  3. Inside the "products" folder, open "delete-product.js" file.

Place the following code inside "delete-product.js" file.

$(document).ready(function(){

    // will run if the delete button was clicked
    $(document).on('click', '.delete-product-button', function(){
		// product id will be here
	});
});

Get product ID

The product ID is needed to identify which record to delete using the API.

Replace "// product id will be here" of the previous section with the following code.

// get the product id
var product_id = $(this).attr('data-id');

Show "delete confirmation" dialog box

This is where we will use the Bootbox.js library. We will show a dialog box with "Are you sure?" message with "Yes" and "No" buttons.

Place the following code after the previous section's code.

// bootbox for good looking 'confirm pop up'
bootbox.confirm({

	message: "<h4>Are you sure?</h4>",
	buttons: {
		confirm: {
			label: '<span class="glyphicon glyphicon-ok"></span> Yes',
			className: 'btn-danger'
		},
		cancel: {
			label: '<span class="glyphicon glyphicon-remove"></span> No',
			className: 'btn-primary'
		}
	},
	callback: function (result) {
		// delete request will be here
	}
});

Delete record using API

If the user clicked "Yes" on the dialog box, a "delete" request will be sent to the API.

Replace "// delete request will be here" of the previous section with the following code.

if(result==true){

	// send delete request to api / remote server
	$.ajax({
		url: "http://localhost/api/product/delete.php",
		type : "POST",
		dataType : 'json',
		data : JSON.stringify({ id: product_id }),
		success : function(result) {

			// re-load list of products
			showProducts();
		},
		error: function(xhr, resp, text) {
			console.log(xhr, resp, text);
		}
	});

}

Output

How To Search Data Using jQuery AJAX?

This feature is part of our LEVEL 2 source code.

Include two JS file in index.html

<!-- products scripts -->
<script src="app/products/products.js"></script>
<script src="app/products/search-product.js"></script>

Create products.js file

The "products.js" file will contain any functions that can be used by other product components like our "read-products.js" or "search-products.js" files.

Open "app" folder. Open "products" folder. Create "products.js" file.

Open the "products.js" file and put the following code.

// product list html
function readProductsTemplate(data, keywords){

    var read_products_html=`
		<!-- search products form -->
		<form id='search-product-form' action='#' method='post'>
		<div class='input-group pull-left w-30-pct'>

			<input type='text' value='` + keywords + `' name='keywords' class='form-control product-search-keywords' placeholder='Search products...' />

			<span class='input-group-btn'>
				<button type='submit' class='btn btn-default' type='button'>
					<span class='glyphicon glyphicon-search'></span>
				</button>
			</span>

		</div>
		</form>

		<!-- when clicked, it will load the create product form -->
		<div id='create-product' class='btn btn-primary pull-right m-b-15px create-product-button'>
			<span class='glyphicon glyphicon-plus'></span> Create Product
		</div>

		<!-- start table -->
		<table class='table table-bordered table-hover'>

			<!-- creating our table heading -->
			<tr>
				<th class='w-25-pct'>Name</th>
				<th class='w-10-pct'>Price</th>
				<th class='w-15-pct'>Category</th>
				<th class='w-25-pct text-align-center'>Action</th>
			</tr>`;

    // loop through returned list of data
    $.each(data.records, function(key, val) {

        // creating new table row per record
        read_products_html+=`<tr>

            <td>` + val.name + `</td>
            <td>$` + val.price + `</td>
            <td>` + val.category_name + `</td>

            <!-- 'action' buttons -->
            <td>
                <!-- read product button -->
                <button class='btn btn-primary m-r-10px read-one-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-eye-open'></span> Read
                </button>

                <!-- edit button -->
                <button class='btn btn-info m-r-10px update-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-edit'></span> Edit
                </button>

                <!-- delete button -->
                <button class='btn btn-danger delete-product-button' data-id='` + val.id + `'>
                    <span class='glyphicon glyphicon-remove'></span> Delete
                </button>
            </td>
        </tr>`;
    });

    // end table
    read_products_html+=`</table>`;

    // inject to 'page-content' of our app
    $("#page-content").html(read_products_html);
}

Create search-product.js file

The "search-product.js" file will contain a code that catches the submission of the "search product" form.

Open "app" folder. Open the "products" folder. Create "search-products.js" file.

Open the "search-products.js" file and put the following code.

$(document).ready(function(){

    // when a 'search products' button was clicked
    $(document).on('submit', '#search-product-form', function(){

        // get search keywords
        var keywords = $(this).find(":input[name='keywords']").val();

        // get data from the api based on search keywords
        $.getJSON("http://localhost/api/product/search.php?s=" + keywords, function(data){

            // template in products.js
            readProductsTemplate(data, keywords);

            // chage page title
            changePageTitle("Search products: " + keywords);

        });

        // prevent whole page reload
        return false;
    });

});

Change read-products.js

We want the "product list" and "search product" to have the same HTML table template. To do this, we will use the readProductsTemplate() function of the products.js file.

Open "app" folder. Open "products" folder. Open the "read-products.js' file. Change the showProducts() function to the following code.

// function to show list of products
function showProducts(){

    // get list of products from the API
    $.getJSON("http://localhost/api/product/read.php", function(data){

        // html for listing products
        readProductsTemplate(data, "");

        // chage page title
        changePageTitle("Read Products");

    });
}

Output

How To Paginate Data Using jQuery AJAX?

This feature is part of our LEVEL 2 and LEVEL 3 source codes.

Change JSON URL

To make pagination work, we'll have to change the JSON URL. The contents of this new JSON data will include the "paging" node. It looks like the following.

So we will change the JSON URL from:

http://localhost/api/product/read.php

to

http://localhost/api/product/read_paging.php

It means we have to change something in our code. See the change in the next section.

Show products using JSON URL

Open /app/products/read-products.js file. Replace the code with the following.

$(document).ready(function(){

    // show list of product on first load
    showProductsFirstPage();

    // when a 'read products' button was clicked
    $(document).on('click', '.read-products-button', function(){
        showProductsFirstPage();
    });

    // when a 'page' button was clicked
    $(document).on('click', '.pagination li', function(){
        // get json url
        var json_url=$(this).find('a').attr('data-page');

        // show list of products
        showProducts(json_url);
    });

});

function showProductsFirstPage(){
    var json_url="http://localhost/api/product/read_paging.php";
    showProducts(json_url);
}

// function to show list of products
function showProducts(json_url){

    // get list of products from the API
    $.getJSON(json_url, function(data){

        // html for listing products
        readProductsTemplate(data, "");

        // chage page title
        changePageTitle("Read Products");

    });
}

Add Pagination HTML

Open /app/products/products.js file. Find the ending "table" tag and put the following code under it.

// pagination
if(data.paging){
    read_products_html+="<ul class='pagination pull-left margin-zero padding-bottom-2em'>";

        // first page
        if(data.paging.first!=""){
            read_products_html+="<li><a data-page='" + data.paging.first + "'>First Page</a></li>";
        }

        // loop through pages
        $.each(data.paging.pages, function(key, val){
            var active_page=val.current_page=="yes" ? "class='active'" : "";
            read_products_html+="<li " + active_page + "><a data-page='" + val.url + "'>" + val.page + "</a></li>";
        });

        // last page
        if(data.paging.last!=""){
            read_products_html+="<li><a data-page='" + data.paging.last + "'>Last Page</a></li>";
        }
    read_products_html+="</ul>";
}

Output

After making the changes above, run index.html again. Do a hard refresh. You should see the paging buttons like the one below.

How To Run The Source Code?

We highly recommend for you to follow and study our well-detailed, step-by-step tutorial above first. Nothing beats experience when it comes to learning.

But we believe you will learn faster if you'll see the final source code as well. We consider it as your additional guide.

Imagine the value or skill upgrade it can bring you. The additional income you can get from your work, projects or business. The precious time you save. Isn't that what you want?

By now, you need to download our source codes. To do it, use any download buttons in the next few sections below.

Once you downloaded the source codes, here's how you can run it.

  1. Extract the files to your server directory.
  2. Set up the "api" by following the README.txt inside the "api" folder.
  3. Open your browser and run index.html
  4. If you can see the list of "product" records, it means your set up is correct.

Download LEVEL 1 Source Code

FEATURES LEVEL 1
Create product YES
Read product YES
Read one product YES
Update product YES
Delete product YES
Bootstrap UI YES
PHP REST API source code YES
FREE email support for 3 months YES
Source code updates via email YES
$20 - Download now

Download LEVEL 2 Source Code

FEATURES LEVEL 2
All features of LEVEL 1 YES
Search products YES
Pagination of products & search products YES
Create category YES
Read category YES
Read one category YES
Update category YES
Delete category YES
Search categories YES
Pagination of categories & search categories YES
Navigation bar YES
FREE email support for 6 months YES
$40 - Download now

Download LEVEL 3 Source Code

FEATURES LEVEL 3
All features of LEVEL 2 YES
Inline editing of products & categories YES
Export CSV of products & categories YES
Bootstrap tooltip on some products & categories buttons YES
FREE email support for 1 year YES
$50 - Download now

Why download?

Do you need more reasons to download it?

MORE REASONS TO DOWNLOAD THE CODE ALL
Use new skills for your multiple projects YES
Save huge amount of time learning jQuery AJAX YES
Code examples are direct to the point YES
Well explained and commented source code YES
Fast and friendly email support YES
Free source code updates YES

What's Next?

Our next topic is a bit different: How To Display Facebook Page Events on Website using PHP?

Related Tutorials

Please explore more tutorials on our start page. Click here.

Some Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

Thanks for reading our AJAX CRUD Tutorial Using jQuery, JSON and PHP!

How to display Instagram Feed on your website using PHP or JavaScript?

Are you looking for a way to display Instagram feed on your website? You probably upload photos, videos, and albums on your Instagram account. And, you have a website as well. Am I right? If that is the case, then it is a good idea to display your Instagram posts on your website!

This is a great way to increase your Instagram followers and engage them in your brand. Today I'm going to show you how to display publicly available Instagram feed on your website using PHP or JavaScript.

3 ways to display Instagram feed on website

I've found out that there are three ways to display Instagram feed on your website. They are the following.

  1. Using the official Instagram API.
  2. Using an alternative API.
  3. Using a website plugin.

I will show you the code how to use those three. Let's dive in!

#1 Using the official Instagram API

On the official documentation, they call this the Instagram Basic Display API. This API allows users to read basic profile information, photos, videos, and albums of the connected account.

  1. Create a Facebook developer account. After you created a developer account, you need to create a Facebook application in the same interface. You can create a Facebook developer account and a Facebook application here.
  2. Configure Instagram's basic display. I think Instagram's documentation is good enough and I don't want to repeat the same instructions here. Follow their getting started guide here.
  3. Get your long-lived access token. By default, Instagram API will give you a short-lived access token which is valid only for 24 hours. If you get your long-lived access token, it will be valid for 60 days. Learn how to get a valid long-lived access token here.

PHP code

Once you got your long-lived access token, use it as the value of the $token variable below. The code below will allow you to display the list of posts

<?php 
// query the user media
$fields = "id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username";
$token = "your_long_lived_user_access_token";
$limit = 10;

$json_feed_url="https://graph.instagram.com/me/media?fields={$fields}&access_token={$token}&limit={$limit}";
$json_feed = @file_get_contents($json_feed_url);
$contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);

echo "<div class='ig_feed_container'>";
    foreach($contents["data"] as $post){
        
        $username = isset($post["username"]) ? $post["username"] : "";
        $caption = isset($post["caption"]) ? $post["caption"] : "";
        $media_url = isset($post["media_url"]) ? $post["media_url"] : "";
        $permalink = isset($post["permalink"]) ? $post["permalink"] : "";
        $media_type = isset($post["media_type"]) ? $post["media_type"] : "";
        
        echo "
            <div class='ig_post_container'>
                <div>";

                    if($media_type=="VIDEO"){
                        echo "<video controls style='width:100%; display: block !important;'>
                            <source src='{$media_url}' type='video/mp4'>
                            Your browser does not support the video tag.
                        </video>";
                    }

                    else{
                        echo "<img src='{$media_url}' />";
                    }
                
                echo "</div>
                <div class='ig_post_details'>
                    <div>
                        <strong>@{$username}</strong> {$caption}
                    </div>
                    <div class='ig_view_link'>
                        <a href='{$permalink}' target='_blank'>View on Instagram</a>
                    </div>
                </div>
            </div>
        ";
    }
echo "</div>"
?>

CSS code

Here's the CSS code I used with the code above.

.ig_feed_container{
    width:100%; margin:0 auto; font-family:Arial, Helvetica, sans-serif;
}

.ig_post_container{
    border: 2px solid #f1f1f1; margin-bottom:25px; margin-left:3%; width:20%; height:550px; float:left;
}

.ig_post_container img{
    width:100%;
}

.ig_post_container .ig_post_details{
    padding:15px;
}

.ig_post_container .ig_view_link{
    margin-top:10px;
}

Output

The output will look like the following.

JavaScript Code

I don't recommend using the direct JSON feed URL with JavaScript code. This will easily reveal your long lived access token in the client side or in any user's browser. If you really want to use JavaScript, I suggest you create your own JSON feed on your server first. Then, you use that JSON feed on your JavaScript code.

Another options is to use a JSON feed from an alternative API. This method will never reveal your private or long-lived access token in any browser.

Do you want less work?

If you think following the Instagram documentation is hard and confusing because there are so many steps to follow and their API changes frequently, you can use an alternative API or a website plugin. This will save you a lot of time and remove headaches.

You don't need to deal with a broken data feed because of an Instagram API update. Disclaimer: The suggested products below, AccentAPI and SociableKIT, are developed by my company Codalify Software Development.

#2 Using an alternative API

To get your Instagram account's data feed, you can use an alternative API like AccentAPI.

What are the advantages of using AccentAPI over the official API?

There are data that the official Instagram API will not give you. AccentAPI will give you those missing data. Also, AccentAPI provides an easy-to-use API, tutorials, and human support. See the comparison table below.

FeaturesAccentAPIOfficial Instagram API
Post likes countYESNO
Post comments countYESNO
Profile biographyYESNO
Profile follower countYESNO
Profile following countYESNO
Profile website URLYESNO
Easy-to-use APIYESNO
Easy-to-follow tutorialYESNO
Human chat & email supportYESNO

How to get the link to your Instagram data feed?

  1. You may pay using this link. Pricing is only $2/month, billed annualy.
  2. Once your payment is received, within 24 hours, our AccentAPI team will reply with a link to your data feed.
  3. We offer a 7-days money-back guarantee.

How to display Instagram feed using PHP?

You need to get your own data feed URL from AccentAPI. Once you have that link, you can use it with the following PHP code.

<?php 
// query the user media
$limit = 10;
$json_feed_url="https://app.accentapi.com/api/instagram/feed?username=coolest.buildings&limit={$limit}";
$json_feed = @file_get_contents($json_feed_url);
$contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);

echo "<div class='ig_feed_container'>";
    foreach($contents["data"] as $post){
        
        $username = isset($post["username"]) ? $post["username"] : "";
        $caption = isset($post["caption"]) ? $post["caption"] : "";
        $media_url = isset($post["media_url"]) ? $post["media_url"] : "";
        $permalink = isset($post["permalink"]) ? $post["permalink"] : "";
        $media_type = isset($post["media_type"]) ? $post["media_type"] : "";
        
        echo "
            <div class='ig_post_container'>
                <div>";

                    if($media_type=="VIDEO"){
                        echo "<video controls style='width:100%; display: block !important;'>
                            <source src='{$media_url}' type='video/mp4'>
                            Your browser does not support the video tag.
                        </video>";
                    }

                    else{
                        echo "<img src='{$media_url}' />";
                    }
                
                echo "</div>
                <div class='ig_post_details'>
                    <div>
                        <strong>@{$username}</strong> {$caption}
                    </div>
                    <div class='ig_view_link'>
                        <a href='{$permalink}' target='_blank'>View on Instagram</a>
                    </div>
                </div>
            </div>
        ";
    }
echo "</div>"
?>

How to embed Instagram feed using JavaScript?

If you want to use JavaScript, here is the code.

Coming soon!

CSS code

The following is the CSS code I used for both the PHP and JavaScript code above.

.ig_feed_container{
    width:100%; margin:0 auto; font-family:Arial, Helvetica, sans-serif;
}

.ig_post_container{
    border: 2px solid #f1f1f1; margin-bottom:25px; margin-left:3%; width:20%; height:550px; float:left;
}

.ig_post_container img{
    width:100%;
}

.ig_post_container .ig_post_details{
    padding:15px;
}

.ig_post_container .ig_view_link{
    margin-top:10px;
}

#3 Using a website plugin

If you do not want to code, use a "no-code" approach. You can use website plugins like SociableKIT.

What are the advantages of using SociableKIT over the AccentAPI?

SociableKIT have many of AccentAPI's great set features like easy-to-follow video tutorials and human chat and email support, and more. See the comparison table below.

FeaturesSociableKITAccentAPI
No need to learn PHP, JavaScript, or CSS.YESNO
Copy a single line of code and paste it on your website.YESNO
Responsive. Your Instagram feed will look great on mobile, tablet, or desktop.YESNO
Easily change the look & feel using lots of customization options.YESNO
Carousel layout, grid layout, lightbox, pop-up options, and more.YESNO
Use Instagram feed, Facebook posts feed, and more in one place.YESNO

How to use SociableKIT?

The following are the steps that you need to take.

  1. Sign up and log in to SociableKIT.
  2. Create a new solution. Select "Instagram feed" on the drop-down.
  3. Enter your Instagram username and click the Next button.
  4. It will show the customization options like layouts, colors, and more.
  5. Click the Save changes button. On the upper right, click the "Embed on website" button.
  6. Copy the code and paste it on your website.

Click here to see an Instagram feed made with SociableKIT.

SociableKIT offers a 7-days free trial. Their pricing is $4/feed/month if you buy 5 feeds. $2.50/feed/month if you buy 10 or more feeds. $8/month if you buy only one feed.

Thank you!

Thank you for learning from CodeOfaNinja! I hope you learned how to add, display, or embed Instagram feed on your website.

How To Display Facebook Page Videos On Website Using PHP?

Let's code!

Do you have a video manager on your website? Do you upload videos on your Facebook page?

If your answer is both YES, you’re wasting a lot of time managing your brand's videos online.

What if there's a way to upload a video ONCE, and then let it appear both on your Website and Facebook page?

Will you be happy saving your precious time?

Our code for today will make you happy then, just like we are!

Today I'm gonna teach you how to display publicly available Facebook Page VIDEOS on your website.This one is great if you want your Facebook page videos to be shown in your website in a synchronized way.

Once you uploaded a video on Facebook, it will be automatically reflected on your website too.

Source Code Overview

Here’s an overview of what our code does:

Gets videos listed with data such as the video itself, video title, description, date posted, etc. from your Facebook fan page without using any Facebook PHP SDK, just the Facebook Graph API!

Display these videos to a webpage (assuming it is your WordPress or PHP website.)

Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here.

Display Facebook Page Videos on Website - Output

BASIC Source Code Output

We have to know where we are going, if we’re done with the code tutorial below, we will achieve this output:

PRO Source Code Output

We used PHP classes and so features are easier to use, more actively improved and added.

See the full list of features in section 10.1 to 10.3 below. It has all the details of these features.

For now, let us learn how the BASIC source code was made. Enjoy the following step by step tutorial!

Get your page access token

Before you can get any data from your Facebook page via the graph API, you need a "page" access token.

Follow this detailed tutorial about how to get a page access token: How to get a Facebook page access token?

Replace YOUR_ACCESS_TOKEN with your page access token.

Create index.php

Create index.php and set the timezone, Facebook page and the page title. Put the following code inside index.php

<?php
// set timezone for servers that requires it
date_default_timezone_set("America/Los_Angeles");

// set Facebook page ID or username
$fb_page_id = "katyperry";

// page title
$page_title = "BASIC - Display Facebook Page Videos on Website";
?>

Enable Bootstrap

Put a Bootstrap-enabled basic HTML after the code on section 4.0.

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo $page_title;></title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

</head>
<body>

<div class="container">

</div> <!-- /container -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

<--[if lt IE 9]-->
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

</body>
</html>

Specify Variables

Specify the values for the following variables:

  • $profile_photo_src so that the Facebook page primary picture will be rendered in thumbnail.
  • $access_token obtained on section 3.0, this will give us the power to get Facebook page videos.
  • $fields are actually column names in Facebook page videos database.
  • $limit the number of videos you want to be displayed on your page.

Put the following code inside the 'container' tags on section 5.0

$profile_photo_src = "https://graph.facebook.com/{$fb_page_id}/picture?type=square";
$access_token = "YOUR_ACCESS_TOKEN ";
$fields = "id,title,description,created_time,from,source";
$limit = 5;

Build JSON Link

Use the variable values on the previous section and construct the $json_link. Get the data from that URL, decode it, and count the number of records it returned.

In short, put the following code after the code in section 6.0

$json_link = "https://graph.facebook.com/v2.6/{$fb_page_id}/videos?access_token={$access_token}&fields={$fields}&limit={$limit}";
$json = file_get_contents($json_link);

$obj = json_decode($json, true);
$feed_item_count = count($obj['data']);

Loop Through Videos

Loop through each records, extract each video information and place it in an HTML structure.

for($x=0; $x<$feed_item_count; $x++){
	echo "<div class='row'>";
		// video source
		$source = $obj['data'][$x]['source'];

		// display Facebook page video
		echo "<lt;div class='col-md-6'>";
			echo "<video controls class='embed-responsive-item'>;
				echo "<source src={$source} type=video/mp4>";
			echo "</video>";
		echo "</div>";

		echo "<div class='col-md-6'>";

			// user's custom message
			$title = isset($obj['data'][$x]['title'])
						? htmlspecialchars_decode($obj['data'][$x]['title'])
						: "Video #" . $obj['data'][$x]['id'];

			$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";
			$description = htmlspecialchars_decode(str_replace("\n", "<br>", $description));

			// when it was posted
			$created_time = $obj['data'][$x]['created_time'];
			$converted_date_time = date( 'Y-m-d H:i:s', strtotime($created_time));
			$ago_value = time_elapsed_string($converted_date_time);

			// from
			$page_id = $obj['data'][$x]['from']['id'];
			$page_name = $obj['data'][$x]['from']['name'];

			// display video title
			echo "<h2 style='margin: 0 0 .5em 0;'>{$title}</h2>";

			// display video description
			echo "<div>";
				echo $description;
			echo "</div>";

			// display when it was posted
			echo "<div style='margin:.5em 0 0 0; color: #999;'>";
				echo "Posted {$ago_value} by <a href='https://facebook.com/{$page_id}' target='_blank'>{$page_name}</a>";
			echo "</div>";

		echo "</div>";

		echo "<div class='col-md-12'>";
			echo "<hr style='margin:2em 0; border:thin solid #f1f1f1;' />";
		echo "</div>";
	echo "</div>";
}

Format Post Date

time_elapsed_string() is a function that will return the "time ago" value, from section 8.0, we pass when the video was posted so that we can display something like: 9 days ago, 9 months ago, a year ago, etc...

Put the following code after the closing 'html' tag.

// to get 'time ago' text
function time_elapsed_string($datetime, $full = false) {

	$now = new DateTime;
	$ago = new DateTime($datetime);
	$diff = $now->diff($ago);

	$diff->w = floor($diff->d / 7);
	$diff->d -= $diff->w * 7;

	$string = array(
		'y' => 'year',
		'm' => 'month',
		'w' => 'week',
		'd' => 'day',
		'h' => 'hour',
		'i' => 'minute',
		's' => 'second',
	);
	foreach ($string as $k => &$v) {
		if ($diff->$k) {
			$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
		} else {
			unset($string[$k]);
		}
	}

	if (!$full) $string = array_slice($string, 0, 1);
	return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Download the Complete Source Code

You can get the source code for free by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the value or skill upgrade it can bring you, or income you can get from your website project or business.

For a limited time only, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE by clicking the green buy button below.

Download BASIC Source Code

FEATURES BASIC
Upload videos on your Facebook page, watch them on your website. YES
Save time figuring out and coding these features on your website. YES
Display video list from your Facebook page. YES
Display video title. If none, display video number. YES
Display video description. YES
Post date with "time ago" format. YES
Display Facebook page name (with link) for each video. (opens in new tab) YES
Bootstrap enabled script. YES
Responsive layout. (great for mobile devices) YES
Free source code updates. YES
Free support for 6 months. YES
Download Now

Download the PRO Source Code

All features of BASIC source code. YES
Display number of likes. YES
Display number of comments. YES
Display some likers and link to their profiles. YES
Display commenters and link to their profile. YES
Display user comments. YES
Show comments and comment replies on pop up. YES
Load more videos automatically when scrolling (infinite scroll). YES
Newly loaded content still has video controls, number of likes, etc. YES
Will say "All videos were loaded." when there’s no content to be loaded. YES
Make links clickable in video description. YES
Make links clickable in user comments. YES
Link to actual Facebook page video post. YES
Likers and commenters are loaded and shown via AJAX YES
Show comments YES
Show more comments, loaded via AJAX YES
Show comment replies YES
Show more comment replies, loaded via AJAX YES
Made with PHP classes YES
Useful class methods & properties YES
4-step easy integration to your website YES
Free support for 1 year. YES
Free source code updates. YES
Download Now

Need more reasons to download?

MORE REASONS TO DOWNLOAD IT
Buy only once, use on unlimited number of websites and Facebook pages! YES
No different kind of licenses. YES
No many different pricing schemes. YES
No monthly or any recurring fees. YES
No need to rely on another website to render Facebook page videos. YES
No need for codes from other websites. YES
You can learn more how to code, I love teaching and can give you free tips! YES
Familiarize yourself with the Facebook Graph API. YES
You get free code and feature updates YES
Tutorial above is always free and updated every Facebook API update. YES
Completely customizable. YES

If you think there's a missing feature, please let us know by sending me a message via email [email protected], or via our official Facebook page! We can work on it!

Thank you for supporting our projects here at codeofaninja.com!

Please provide your Facebook page URL on the message, thanks!

What's Next?

Today we have learned how to show your Facebook page videos on your website.

Did you know that you can also display Facebook Timeline feed on your website?

Let us go to the next tutorial: How To Display Facebook Page POSTS on Website?

Related Source Codes

Did you know that you can also display other social media data on your website? I’ve created tutorials on them too, see the following:

Social Media Script Tutorials
Display Facebook Page EVENTS on Website
Display Facebook Page PHOTOS on Website
Display Facebook Page VIDEOS on Website
Display Facebook Page POSTS on Website
Display Instagram FEED On Your Website
Display Twitter FEED on Website
Display Google+ FEED on Website

Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email [email protected], or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

  • 1. Subscribe to social media scripts tutorial news and updates.
  • 2. Be updated about what works and what does not work on social media APIs.
  • 3. Be notified for any related social media API updates.
100% Privacy. We will never spam you!

#3 Thank You!

Thanks for visiting our tutorial on how to display Facebook page videos on website using PHP and Facebook Graph API!