Posts

php-login-system
Home PHP

PHP Login System & User Management 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!

Source Code LIVE DEMO

If you need the live demo link, send a request to mike@codeofaninja.com with subject “Login System Demo Link Request”, thank you!

PHP Login System Features

You can see the features and download it below.

FeatureLogin System
Login form with email and passwordYES
PHP Sessions are used to identify logged in and logged out users.YES
Hashed password stored in databaseYES
Register formYES
Password and confirm password fieldsYES
Check if password matchesYES
Sending of verification link to emailYES
Validation page of email linkYES
Check if password is strong enoughYES
Email sending works with remote host only.YES
Redirection to login page if not yet logged inYES
Forgot password pageYES
Password reset link sent to emailYES
Password reset pageYES
Customer access to index page when logged inYES
Customer access to edit profile page when logged inYES
Customer change password pageYES
Customer password and confirm password field when editing profileYES
Customer logoutYES
Admin create userYES
Admin read usersYES
Admin update userYES
Admin delete userYES
Admin change of user access level: Admin or CustomerYES
Admin search user by email addressYES
Admin users list pagingYES
Admin edit profileYES
Admin logoutYES
Admin change password pageYES
Admin can change user passwordsYES
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 interfaceYES
Free source code updates and support for 6 months.YES

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 mike@codeofaninja.com, 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!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. Get a FREE EBOOK as well. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

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

web-programming-source-codes-with-tutorials
Home Lists+

30+ Useful Web Programming Source Codes with Tutorials – Download Now!

web-programming-source-codes-with-tutorials
The following web programming source codes with tutorials can be very useful to further improve your web programming skills.

The source code package contains 30+ useful web programming source codes with tutorials. If you are just starting to learn web programming with HTML, CSS, JavaScript, jQuery and PHP – you can learn faster with our source code examples.

If you have any questions about the code, you can reach us for professional help. I will personally answer your concerns.

You can get the source codes in the package for free. How? By following each of our tutorials. 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 source code package, 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

Click here if you want to learn more about why our tutorials are free and always will be free, but source code downloads are paid.

What will you get?

You will be able to download the 30+ useful web programming source codes. For a limited time, I will give you the source code for a low price. Download the source code package you desire by clicking the BUY button.

Web programming source codes with tutorials
jQuery Step By Step Tutorial for Beginners
A Quick Way To Create A Vertical Accordion With jQuery
Two Example Usage of jQuery On() Method
jQuery AJAX Post Example with PHP and JSON
jQuery Redirect onClick Event (New or Same Window)
Simple jQuery Drop Down Menu Tutorial with Source Code and Live Demo
CSS and jQuery Sliding Drawer Navigation Tutorial, an Android Look-Alike
jQuery: Sum TextBox Values As You Type
Solving Your Table Row Data’s Long List Of Options
FbAlbumPreview jQuery Plugin
Google Plus Style Notification Box Tutorial
Convert a DIV Area to an Editable HTML Form
Check and Validate Username Without Page Refresh
Data Searching Without Page Refresh
Check or Uncheck Checkboxes with jQuery And Get Selected with PHP
How To Use Table Sorter With A Database
Add or Remove File Field Then Upload File in PHP and jQuery
How To Use Lightbox With A Database
Dynamic Pie Chart in PHP or JavaScript with MySQL?
Apache .htaccess RewriteRule Examples with PHP for Clean URLs
Data Searching Without Page Refresh
Simple PHP Pagination Script to Handle Your Growing Data
Paginating Your Data with jQuery AJAX and Awesome PHP Pagination Class
Dynamic and Dependent Drop Down Menu with PHP, MySQL and jQuery
jQuery UI Tutorial for Beginners with Examples
jQuery UI Dialog Example with Source Code Downloads
jQuery UI Autocomplete Example
Sample Use of JavaScript OnFocus and OnBlur Event
Vertical TinyDropdown 2 Example
Move Options Between Two Select Boxes
JavaScript Array CRUD Example
Salt, Hash and Store Passwords Securely with Phpass
Google Maps Geocoding Example with PHP
Working with Geolocation watchPosition() API
Step by Step Bootstrap Tutorial for Beginners
Coding A Responsive Website Design
TextBox with Search Icon in HTML and CSS

Thanks for reading our 30+ Useful Web Programming Source Codes with Tutorials!

paypal-integration-in-php
Home PHP

PayPal Integration In PHP – Source Code Download!

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.

Live Demo

If you still need a live demo after watching our demo video above, send and email request to mike@codeofaninja.com with a subject “DEMO: PayPal Integration in PHP”.

Live 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.

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

[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.

FeatureAdd On
Pay with PayPalYES
Pay with credit card (via PayPal)YES
Pay with debit card (via PayPal)YES
Set merchant email address / PayPal IDYES
Set currency and currency symbolYES
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 siteYES
Free support for 6 monthsYES

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 mike@codeofaninja.com
b. Go to https://fb.com/codeofaninja and chat me up.

Home PHP

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 a 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 of 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.

Download Now

Contents of this post include:

1.0 Source Code Overview
2.0 Output Preview & Demo Link
3.0 Is This Code For Me?
4.0 Pre-Requisites
5.0 Cart Data Storage
6.0 Database Design
7.0 File Structure
8.0 What People Say
9.0 Features List & Download
10.0 Simple Set Up
11.0 Thanks For Your Help!
12.0 Related Source Codes
13.0 Get In Touch

1.0 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 are 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 on section 9.0 below.

2.0 Output Preview & Demo Link

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.

Output preview when customer is not logged in.


Output preview when customer is logged in.


Output preview when admin / merchant is logged in.


If you need the live demo link, send a request to mike@codeofaninja.com with subject “DEMO Request: PHP Shopping Cart System”, thank you!

3.0 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.

4.0 Pre-Requisites

Before you download, make sure you have 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!

5.0 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 site visitor’s user_id locally.
  • We use PHP SESSIONS as back up just in case cookies are disabled in user’s browser.
  • We use MySQL to store cart items in the database.
  • This way, cart items can be resurrected even if 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.

6.0 Database Design

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

7.0 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

8.0 What People Say

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

9.0 Features List & Download

FEATUREACCESS LEVELSOURCE CODE
USER MANAGEMENT
Create userAdminYES
Read usersAdminYES
Update userAdminYES
Delete userAdminYES
Search userAdminYES
Users list paginationAdminYES
Valid email format requiredAdmin & CustomerYES
Password must be uppercase letter, lowercase letter, number and special characterAdmin & CustomerYES
Confirm password fieldAdmin & CustomerYES
Password validation as you typeAdmin & CustomerYES
View customer order historyAdmin & CustomerYES
Deleting first administrator account is not allowedAdminYES
User types: Admin and CustomerAdmin & CustomerYES
Interface for adminAdminYES
Interface for customerCustomerYES
Login pageAdmin & CustomerYES
Log outAdmin & CustomerYES
Sign up pageCustomerYES
Sign up email notification with validation linkCustomerYES
Edit profile of currently logged in userAdmin & CustomerYES
Show name with icon of currently logged in userAdmin & CustomerYES
Forgot password – system can send unique reset password link via emailCustomerYES
Forgot password – user can click the unique verification link and reset his passwordCustomerYES
PRODUCT MANAGEMENT
Create productAdminYES
Read productsAdminYES
Update productAdminYES
Delete productAdminYES
Search productAdmin & CustomerYES
Product lists with paginationAdmin & CustomerYES
View inactive productsAdminYES
View products under a categoryAdmin & CustomerYES
Product list under a category with paginationAdmin & CustomerYES
Upload product images, you can select many images at onceAdminYES
View product images with thumbnailsAdmin & CustomerYES
Delete product image with X iconAdminYES
Upload product PDFs , you can select many PDF files at onceAdminYES
List product PDFAdminYES
Delete product PDFAdminYES
View single product with related informationCustomerYES
View single product with add to cart buttonCustomerYES
View single product with image sliderCustomerYES
View single product with SEO friendly URL (.htaccess file used)CustomerYES
Rich text editor for product description when adding or editing productAdminYES
Quantity value must be more than 1CustomerYES
Sorting by fieldsAdmin & CustomerYES
VARIATION MANAGEMENT
Set variation nameAdminYES
Set variation priceAdminYES
Set variation stockAdminYES
Stock / inventory decreases when order has been placedAdminYES
Increase stock / inventory by updating the variationAdminYES
Create variationAdminYES
Read list of variationAdminYES
Update variationAdminYES
Delete variationAdminYES
CATEGORY MANAGEMENT
Create categoryAdminYES
Read categoriesAdminYES
Update categoryAdminYES
Delete categoryAdminYES
Search categoryAdminYES
Category list with paginationAdminYES
Category search result with paginationAdminYES
View products under a product categoryAdmin & CustomerYES
Auto update category drop down in create or update product formAdminYes
Auto update categories in navigation barAdmin & CustomerYES
Highlight selected category in navigationAdmin & CustomerYES
ORDER MANAGEMENT
Make an orderCustomerYES
Auto-generated unique transaction IDCustomerYES
Add to cart button (for each item) with specified quantityCustomerYES
Cart page with list of products added to cartCustomerYES
Update quantity button for each item in cart pageCustomerYes
Auto-compute subtotal in cart pageCustomerYES
Auto-compute grand total in cart pageCustomerYES
Remove from cart button for each item in the cartCustomerYES
Empty cart button to remove all items in the cartCustomerYES
View order history of a customerAdmin & CustomerYES
View pending and completed order in separate tabsAdminYES
Checkout pageCustomerYES
Show billing information on check-out pageCustomerYES
Edit billing information button on checkout pageCustomerYES
Show payment information on checkout pageCustomerYES
Payment via cash on deliveryCustomerYES
Payment via PayPalCustomerYES
Place order page – Thank you messageCustomerYES
View list of ordersCustomerYES
Pagination on list of ordersAdmin & CustomerYES
Latest order seen at the top of the listAdmin & CustomerYES
View details of an orderAdmin & CustomerYES
Auto-compute order totalsAdmin & CustomerYES
Change status of an order (pending or completed)AdminYES
SECURITY
Register user hashed password stored in the databaseCustomerYES
Edit user profile hashed password update in the databaseAdminYES
Create user hashed password stored in the databaseAdminYES
Login user with hashed password validationCustomer & AdminYES
Used PDO bindParam() to prevent SQL injection in all MySQL queriesDeveloperYES
Used PHP htmlspecialchars() to prevent XSS attacksDeveloperYES
WEB PAGE MANAGEMENT
Create pageAdminYES
Read pageAdminYES
Update pageAdminYES
Delete pageAdminYES
Search pageAdminYES
Pages list with paginationAdminYES
Pages search result with paginationAdminYES
CONTACT MANAGEMENT
Send message to AdminCustomerYES
Display other ways to contact AdminCustomerYES
Display list of messagesAdminYES
Messages list with paginationAdminYES
Read messageAdminYES
Delete messageAdminYES
Search messageAdminYES
Messages search result with paginationAdminYES
MORE REASONS TO DOWNLOAD IT
Object oriented programming source codeDeveloperYES
Bootstrap user interfaceDeveloperYES
PDO extension usedDeveloperYES
Page title navigation with linksDeveloperYES
Radio button looks like a switchDeveloperYES
Icon in all create, edit and delete buttonsDeveloperYES
All source code files organized by foldersDeveloperYES
Database configuration file in config folderDeveloperYES
SQL file and READ-ME.txt that contains login credentials in “sql” folderDeveloperYES
Well explained / commented source codeDeveloperYES
One-time payment, no recurring paymentDeveloperYES
UPDATES AND SUPPORT
Free source code updates for 2 yearsDeveloperYES
Free support for 6 monthsDeveloperYES
Download Now

10.0 Simple Set Up

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

10.1 Run the Home Page

The home page of this source code is NOT index.php – the home page is products.php, so how do we run products.php successfully?

1. In your PhpMyAdmin, create a database with a name “shop_cart_complete”.

2. Import the “shop_cart_complete.sql” SQL file from the “dev” folder.

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

4. Configure $home_url in /config/core.php, example $home_url values are:

$home_url="https://www.yourwebsite.com/"

or

$home_url="http://localhost/shopping-cart-system/"

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

private $host = "localhost";
private $db_name = "shop_cart_complete";
private $username = "shop_complete";
private $password = "your_db_pw_143";

6. Try to login by running login.php and using the following login credentials.

Admin Section Login
Username: mike@example.com
Password: ninja12qw!@QW

Customer Account Login
Username: darwin@example.com
Password: darwin12qw!@QW

10.2 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 PayPal Sandbox mode:

  1. Open /libs/php/paypal_checkout.php
  2. 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">';
    
  3. Change email address in line 5 to your real PayPal account email address. Payment will be sent to the specified PayPal account.

10.3 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"},

10.4 Some More Notes

1. This system works with PHP 5.4+

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

11.0 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.

Download Now

12.0 Related Source Codes

13.0 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 mike@codeofaninja.com, you can also contact me via our official Facebook page.

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 for PHP shopping cart source code download page!

display-google-plus-posts-on-website

How To Display Google Plus Posts On Website Using PHP? Step By Step Guide!

display-google-plus-posts-on-website
Millions of people still use Google+ because of its search engine optimization benefits and additional traffic for their websites.

Do you use Google+ profile or page 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 Google+ feed or posts on your website.

Our script for today will allow you to customize the look and feel of your Google+ posts.

Don’t get me wrong, it looks good!

But sometimes, our design scheme or our clients have a different requirement, they want the Google+ feed to look different.

The good news is, our code for today will help you do it!

Today’s post will cover the following content:

1.0 Source Code Overview
2.0 Final Output Demo
3.0 Obtain an API Key From Google
4.0 Create The index.php File
5.0 Activate Error Reporting And Put Page Title
6.0 Put Container Tags
7.0 Get Google+ ID
8.0 Require Google Libraries and Instantiate Classes
9.0 Retrieve Google+ Posts
10.0 Create items_template.php
11.0 Set Needed Variables
12.0 Format And Show Values To User
13.0 Show Profile Info
14.0 Show Post Message
15.0 Show Post Content
16.0 Show +1 & Comments Count
17.0 Put Custom CSS
18.0 Download The Source Code
19.0 Do You Want a Demo?
20.0 Social Media Scripts – LEVEL 3 – PRO PACK
21.0 Related Source Code
22.0 Some Notes

Let’s get started!

1.0 SOURCE CODE OVERVIEW

Here’s an overview of what our code does:

1.1 It gets a Google+ information and posts from a specified Google+ profile or page. We’ll try Taylor Swift’s Google+ page in the demo.

1.2 Display these Google+ data to a webpage (assuming it is your WordPress or PHP website.)

1.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.

2.0 FINAL OUTPUT DEMO

2.1 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:

2.2 LEVEL 2 Source Code Output

3.0 Obtain an API Key From Google

3.1 Go to https://console.developers.google.com

3.2 Click the “Credentials” tab on the left menu.

3.3 Click the blue “Create Credentials” button

3.4 On the dropdown, click “API Key”

3.5 On the pop up, click the “Browser Key” button. It should look like the following.

create-google-api-key

3.6 Enter your browser API key name and click “Create”.

3.7 You should be able to view and copy your API key on the list.

google-api-key-list

4.0 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><?php echo $page_title; ?></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>

5.0 Activate Error Reporting And Put Page Title

At the top of our index.php file, put the following code.

<?php
// show any kind or errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

// page title
$page_title = "Display Google Plus Feed - LEVEL 1 - Live Demo";
?>

6.0 Put Container Tags

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'>
	<?php echo "<h1 class='page-header'>{$page_title}</h1>"; ?>
	</div>
</div>

7.0 Get Google+ ID

This defines which Google+ page of profile the data will come from. Put the following code inside the col-lg-12 div tag on section 6.0.

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

8.0 Require Google Libraries and Instantiate Classes

Create “libs/php/” directory. Download the Google APIs Client Library for PHP. Extract and copy the files to your “libs/php/” directory. Put the following code below section 7.0 code.

require_once 'libs/php/google-api-php-client/src/Google/autoload.php';
require_once 'libs/php/google-api-php-client/src/Google/Service/Plus.php';

$client = new Google_Client();
$client->setDeveloperKey("CHANGE_TO_YOUR_KEY");

$plus = new Google_Service_Plus($client);
$activities = $plus->activities->listActivities("+".$gplus_id, "public");

9.0 Retrieve Google+ Posts

$items=$activities['modelData']['items'];
include_once "items_template.php";

10.0 Create items_template.php

Section 9.0 will not work without items_template.php, create this file. It will have the following code.

foreach($items as $item){

}

11.0 Set Needed Variables

Inside the foreach loop of section 10.0, put the following code.

$profile_photo=$item['actor']['image']['url'];
$profile_link=$item['actor']['url'];
$page_name=$item['actor']['displayName'];
$verb=$item['verb'];
$link=$item['url'];
$content=$item['object']['content'];
$object_type=isset($item['object']['attachments'][0]['objectType']) ? $item['object']['attachments'][0]['objectType'] : "";
$object_display_name=isset($item['object']['attachments'][0]['displayName']) ? $item['object']['attachments'][0]['displayName'] : "";

$content_image=isset($item['object']['attachments'][0]['fullImage']['url']) ? $item['object']['attachments'][0]['fullImage']['url'] : "";

$replies_count=$item['object']['replies']['totalItems'];
$plusoners_count=$item['object']['plusoners']['totalItems'];

$created_time=$item['published'];
$converted_date_time = date( 'Y-m-d H:i:s', strtotime($created_time));

12.0 Format And Show Values To User

Put the following code below the code on section 11.0, this will show the formatted values of a Google+ post.

echo "<div class='item_box'>";
	echo "<div class='row'>";
	
		// left side
		echo "<div class='col-md-4'>";
			echo "<div class='profile-info'>";
				// SHOW PROFILE INFO HERE
			echo "</div>"; // end 'profile-info'
			
			echo "<p class='profile-message'>";
				// SHOW POST MESSAGE
			echo "</p>";
		echo "</div>"; // end left side 'col-md-4'
		
		// right side
		echo "<div class='col-md-8'>";
		
			echo "<a href='{$link}' target='_blank' class='post-link'>";
				
				echo "<div class='post-content'>";
					// SHOW POST CONTENT
				echo "</div>"; // end 'post-content'
			echo "</a>"; // end 'post-link'
			
			
			echo "<div class='like-count-sum post-content' style='padding:.3em; margin:1em 0; background-color:#eeeeee;'>";
				// SHOW +1 & COMMENTS COUNT
			echo "</div>"; // end 'like-count-sum'
			
			
		echo "</div>"; // end right side 'col-md-8'
		
	echo "</div>"; // end 'row'
	
	echo "<hr />";
echo "</div>"; // end 'item_box'

13.0 Show Profile Info

Replace // SHOW PROFILE INFO HERE comment (in section 12.0) with the following code.

echo "<div class='profile-photo'>";
	echo "<img src='{$profile_photo}' />";
echo "</div>"; // end 'profile-photo'

echo "<div class='profile-name'>";
	echo "<div>";
		echo "<a href='{$profile_link}' target='_blank' style='font-weight:bold; color:#000000;'>{$page_name}</a> ";
		if($verb=="post"){ 
			echo "shared a post";
		}
		
		// it is a reshare
		if($verb=="share"){ 
			echo "reshared a <a href='{$link}' target='_blank'>post</a>";
		}							
	echo "</div>";
	echo "<div class='time-ago'>{$converted_date_time}</div>";
echo "</div>"; // end 'profile-name'

14.0 Show Post Message

Replace // SHOW POST MESSAGE comment (in section 12.0) with the following code.

echo isset($item['annotation']) ? "<div class='post-message'>{$item['annotation']}</div><hr />" : "";
echo isset($item['object']['content']) ? "<div class='post-message'>{$item['object']['content']}</div>" : "";

15.0 Show Post Content

Replace // SHOW POST CONTENT comment (in section 12.0) with the following code.


// normal post
if(!empty($content_image)){
	echo "<img src='{$content_image}' />";
}

// if content is an album
if($object_type=="album"){
	foreach($item['object']['attachments'][0]['thumbnails'] as $thumbnail){
		echo "<img src='{$thumbnail['image']['url']}' style='width:49%; float:left; margin:2px;' />";
	}
}

// if content is a video
if($object_type=="video"){
	echo "<img src='{$item['object']['attachments'][0]['image']['url']}' />";
}

// if content is an event
if($object_type=="event"){
	echo "<div class='post-status'>View on Google+</div>";
}

// if content is an activity
if($object_type=="article"){
	echo "<div class='post-status'>{$object_display_name}</div>";
}

// if not attachments was set
if(!isset($item['object']['attachments'])){
	echo "<div class='post-status'>View on Google+</div>";
}

16.0 Show +1 & Comments Count

Replace // SHOW +1 & COMMENTS COUNT comment (in section 12.0) with the following code.

echo "<div style='float:left; margin:0 .6em 0 0;'>";
	echo "<span class='glyphicon glyphicon-thumbs-up'></span> {$plusoners_count}";
echo "</div>";

echo "<div style='float:left; margin:0 .6em 0 0;'>";
	echo "<span class='glyphicon glyphicon-comment'></span> {$replies_count}";
echo "</div>";

17.0 Put Custom CSS

Put the following code in before the ending head tag of index.php

<style>
.profile-info{
	overflow:hidden;
}

.profile-photo{
	float:left;
	margin:0 .5em 0 0;
}

.profile-photo img{
	width:40px; height:40px;
}

.profile-name{
	float:left;
	width:85%;
}

.time-ago{
	color:#999;
}

.profile-message{
	margin:1em 0;
}

.post-link{
	text-decoration:none;
}

.post-content{
	background: #f6f7f9; border: 1px solid #d3dae8; overflow:hidden;
}

.post-content img{
	width:100%;
}

.post-status{
	margin:.5em; font-weight:bold;
}

.post-picture{
	width:25%; float:left;
}

.post-info{
	width:70%; float:left; margin:.5em;
}

.post-info-name{
	font-weight:bold;
}

.post-info-description{
	color:#999;
}
</style>

18.0 Download 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.

18.1 Download LEVEL 1 Source Code

FEATURESLEVEL 1
Works with Google+ page or profileYES
Specify Google+ ID where to get postsYES
Show Google+ profile pic in postsYES
Show Google+ profile name in postsYES
Google+ profile name has link to Google+ profileYES
Show post dateYES
Show photo thumbnails in albums object typeYES
Links in posts are clickableYES
Hashtags in posts are clickableYES
Identify if a post is a share or reshareYES
Bootstrap enabledYES
Show post annotation and object contentYES
Show +1s countYES
Show comments countYES
Bootstrap enabledYES
Mobile friendlyYES
Download Now

18.2 Download The LEVEL 2 Source Code

FEATURESLEVEL 2
All features of the LEVEL 1 source codeYES
Show post date in “Time ago” formatYES
+1, comment and re-share counts has comma-separated formatYES
Show reshare countYES
Identify post object types: album, photo, video, article, event or note.YES
Show which object type was reshared: album, photo, video, article, event or note.YES
Timeline viewYES
Different icons for each object types in timeline viewYES
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 Google+ 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 Google+ 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 Google+ API.YES
Tutorial is always updated, and you get it for free.YES
Completely customizable.YES

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

19.0 Do You Want a Demo?

If you want a demo to see if this will work with your own Google+ account, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please provide your Google+ link on the message, thanks!

20.0 Social Media Scripts – LEVEL 3 – PRO PACK

Social Media Scripts - LEVEL 3 - PRO PACK
ITEMOriginal CostLEVEL 3 PRO PACK
Display Facebook EVENTS on Website$49.99YES
Display Facebook PHOTOS on Website$49.99YES
Display Facebook VIDEOS on Website$49.99YES
Display Facebook FEED on Website$49.99YES
Display Instagram FEED On Your Website$49.99YES
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.99YES
Display Google+ FEED on Website$29.99YES
BUY TO DOWNLOAD LEVEL 3 PRO PACK NOW USING
Read more about this package. * You can use your debit or credit card with PayPal.

21.0 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 EVENTS on Website
Display Facebook PHOTOS on Website
Display Facebook VIDEOS on Website
Display Facebook TIMELINE on Website
Display Instagram FEED On Your Website
Display Twitter FEED on Website
Display Google+ FEED on Website

22.0 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 mike@codeofaninja.com, 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!

Thank you for reading our tutorial on how to display Google+ feed on website using PHP!

AngularJS CRUD Example with Material Design – Step by Step Guide!


Previously, we learned how to create, read, update and delete database records with our React CRUD Tutorial. Today, we will learn how to do the same CRUD operations with AngularJS, Angular Material and REST API.

Contents of this tutorial include:

1.0 Tutorial Overview
2.0 Program Output – AngularJS CRUD Example
3.0 Set Up The REST API

4.0 Basic Files & Folders
4.1 File Structure
4.2 Create index.html file
4.3 Include Angular Material, Roboto Font and Custom CSS
4.4 AngularJS and Angular Material JavaScript
4.6 Custom JavaScript
4.7 Place AngularJS app container
4.8 Output

5.0 How To Read JSON Data Using AngularJS?
5.1 Create Template for products list
5.2 Create “products” controller
5.3 Create “products” factory
5.4 Output

6.0 How To Create or 6Insert Data Using AngularJS?
6.1 Add “create” product button
6.2 Show “create product” form in dialog box
6.3 Create dialog controller
6.4 Create “create_product” HTML form template
6.5 Add “createProduct” method in controller
6.6 Clear form contents
6.7 Show messages to user
6.8 Add “createProduct” method in factory
6.9 Output

7.0 How To Read One Data Using AngularJS?
7.1 Add “Read One” button in products list
7.2 Show product information in dialog box
7.3 Create “read_one_product.template.html” file
7.4 Add “readOneProduct” method in factory
7.5 Output

8.0 How To Update Data Using AngularJS?
8.1 Add “Edit” button in products list
8.2 Show editable product information in dialog box
8.3 Create “update_product.template.html” file
8.4 Add “updateProduct” method in controller
8.5 Add “updateProduct” method in factory
8.6 Output

9.0 How To Delete Data Using AngularJS?
9.1 Add “delete” button in products list
9.2 Ask user to confirm product deletion
9.3 Add “deleteProduct” function in controller
9.4 Add “deleteProduct” function in factory
9.5 Output

10.0 How To Search Data Using AngularJS?
10.1 Allow users to type search keywords
10.2 Add “searchProducts” function in controller
10.3 Add “searchProducts” function in factory
10.4 Output

11.0 How To Run The Source Code?
12.0 Download LEVEL 1 Source Code
13.0 Download LEVEL 2 Source Code

14.0 What’s Next?
15.0 Related Source Codes
16.0 Notes

1.0 Tutorial Overview

What is AngularJS? It is one of the leading framework for building large JavaScript applications that are easy to maintain.

It makes the development faster because we can implement useful concepts like dependency injection, two-way data binding, reusable code and unit testing.

This tutorial will focus on creating, reading, updating, deleting and searching database records. We will do it using AngularJS and Angular Material as it’s user interface component.

JSON data will be handled by the REST API built using PHP.

2.0 Program Output – AngularJS CRUD Example

2.1 LEVEL 1 Source Code Output


2.2 LEVEL 2 Source Code Output


The LEVEL 2 source code output 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!

3.0 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 AngularJS, 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 AngularJS app. The list of products will be displayed in the page with buttons like “Read One”, “Update” and “Delete”. You will see it in the “How To Read JSON Data Using AngularJS?” section of this tutorial.

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

4.0 Basic Files & Folders

4.1 File Structure

At the end of this tutorial, we will have the following file structure.
├─ app/
├─── assets/
├────── css/
├───────── custom.css
├─── products/
├────── create_product.template.html
├────── products.controller.js
├────── products.factory.js
├────── read_one_product.template.html
├────── read_products.template.html
├────── update_product.template.html
├─── app.js
├─ index.html

4.2 Create index.html file

Create index.html file. Open that file and put the following basic HTML code.

<!DOCTYPE html>
<html>
<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>

</head>
<body>

<!-- app container will be here -->

</body>
</html>

4.3 Include Angular Material, Roboto Font and Custom CSS

We are going to use CSS files from Google CDN. Place the following code inside “head” tag, under “title” tag of the previous section.

<!-- angular material style sheet -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">

<!-- roboto font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">

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

Our “custom.css” file does not exist yet so we have to create it. We will put some CSS as well to style some parts of our application.

  1. Create “app” folder.
  2. Inside “app” folder, create “assets” folder.
  3. Inside “assets” folder, create “css” folder.
  4. Inside “css” folder, create “custom.css” file.
  5. Open “custom.css” file and place the following code.
md-dialog{ width:50%; }
.m-20px-0{ margin:20px 0; }
.m-b-20px{ margin-bottom:20px; }
.m-b-0px{ margin-bottom:0px; }
.md-info{ background-color:#2196F3 !important; color:#ffffff !important; }
.md-danger{ background-color:#D32F2F !important; color:#ffffff !important; }
.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-20-pct{ width:20%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-50-pct{ width:50%; }
.w-60-pct{ width:60%; }
.w-70-pct{ width:70%; }
.w-80-pct{ width:80%; }
.w-90-pct{ width:90%; }
.w-100-pct{ width:100%; }
.t-a-c{ text-align:center; }
.t-a-l{ text-align:left; }
.margin-bottom-1em{ margin-bottom:1em; }

4.4 AngularJS and Angular Material JavaScript

We are going to use AngularJS JavaScript files from Google CDN. Place the following code before the closing “body” tag.

<!-- include angular js -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

<!-- needed for angular material -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>

<!-- angular material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>

4.6 Custom JavaScript

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

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

<!-- products controller -->
<script type="text/javascript" src="app/products/products.controller.js"></script>

<!-- products factory -->
<script type="text/javascript" src="app/products/products.factory.js"></script>

The JavaScript files above does not exist yet so we will create it.

  1. Open “app” folder.
  2. Inside “app” folder, create “app.js” file.
  3. Inside “app” folder again, create “products” folder.
  4. Inside “products” folder, create “products.controller.js” and “products.factory.js” files.

Open “app.js” file and place the following code.

var app = angular.module('myApp', ['ngMaterial']);

We added ‘ngMaterial’ parameter to enable our Angular Material user interface. We will explain and place AngularJS codes inside “products.controller.js” and “products.factor.js” files as we progress in this tutorial.

4.7 Place AngularJS app container

The “read_products.template.html” will hold the template for displaying list of products.

Find

<!-- app container will be here -->

in index.html and replace it with the following code.

<!-- container of our app -->
<div class="container" ng-app="myApp">

    <!-- read products template -->
    <ng-include src="'./app/products/read_products.template.html'"></ng-include>

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

The “read_products.template.html” file does not exist yet so we will create it.

  1. Open “app” folder.
  2. Inside “app” folder, open “products” folder.
  3. Inside “products” folder, create “read_products.template.html” file.

4.8 Output

After doing all the steps above. The output is a blank page. Yes, a blank page for now. But for sure, we will see something here after you complete the next section.

5.0 How To Read JSON Data Using AngularJS?

5.1 Template for products list

Open “read_products.template.html” file and place the following code.

<div layout="row" ng-controller="productsController" ng-cloak>
    <div flex="10"></div>

    <div flex="80" class='m-20px-0'>

        <!-- page title & 'create product' button -->
        <md-toolbar class="md-hue-2">
            <div class="md-toolbar-tools">
                <!-- page title -->
                <div flex md-truncate>
                    <h3 class="md-headline">Products</h3>
                </div>

                <!-- 'create' product button will be here -->
            </div>
        </md-toolbar>

        <!-- 'search' bar will be here -->

        <md-content flex>
            <!-- show product record list -->
            <md-list ng-init="readProducts()">
                <md-list-item class="md-3-line" ng-repeat="product in products">

                    <!-- product information -->
                    <div class="md-list-item-text">
                        <h3>{{product.name}}</h3>
                        <h4>{{product.description}}</h4>
                        <p>${{product.price}}</p>
                    </div>

                    <!-- 'read one', 'edit' and 'delete' buttons -->
                    <div class="md-secondary-container">
						<!-- 'read one' button will be here -->
						<!-- 'edit' button will be here -->
						<!-- 'delete' button will be here -->
                    </div>
                    <md-divider ng-if="!$last"></md-divider>
                </md-list-item>
            </md-list>
        </md-content>
    </div>

    <div flex="10"></div>
</div> <!-- end row -->

5.2 Create “products” controller

  1. Open “app” folder.
  2. Inside “app” folder, open “products” folder.
  3. Inside “products” folder, create “products.controller.js” file.
  4. Open “products.controller.js” file and place the following code.
app.controller('productsController', function($scope, $mdDialog, $mdToast, productsFactory){

	// read products
	$scope.readProducts = function(){

		// use products factory
		productsFactory.readProducts().then(function successCallback(response){
			$scope.products = response.data.records;
		}, function errorCallback(response){
			$scope.showToast("Unable to read record.");
		});

	}
	
	// showCreateProductForm will be here
	
	// DialogController will be here
});

5.3 Create “products” factory

Why do we use “factory” in AngularJS? We use it to make the code reusable.

Methods in factories can be used in different controllers or parts of your application. If there will be a need for change, you don’t have to go and change several parts of the application that uses the same code.

  1. Open “products.factory.js” file.
  2. Create “products.factory.js” file and place the following code.
app.factory("productsFactory", function($http){

    var factory = {};

    // read all products
    factory.readProducts = function(){
        return $http({
            method: 'GET',
            url: 'http://localhost/api/product/read.php'
        });
    };
	
	// createProduct will be here
	
	return factory;
});

5.4 Output

You should see the list of products. Each row should have product name, description and price.

6.0 How To Create or Insert Data Using AngularJS?

6.1 Add “create” product button

We need this button to show a form where user can enter new product information.

  1. Open “read_products.template.html”.
  2. Find
    <!-- 'create' product button will be here -->
  3. Replace it with the following code.
<!-- button for creating product -->
<md-button class="md-raised" ng-click="showCreateProductForm()">Create</md-button>

6.2 Show “create product” form in dialog box

  1. Open “products.controller.js” file.
  2. Find “// showCreateProductForm will be here” and replace it with the following code.
// show 'create product form' in dialog box
$scope.showCreateProductForm = function(event){

	$mdDialog.show({
		controller: DialogController,
		templateUrl: './app/products/create_product.template.html',
		parent: angular.element(document.body),
		clickOutsideToClose: true,
		scope: $scope,
		preserveScope: true,
		fullscreen: true // Only for -xs, -sm breakpoints.
	});
}

// createProduct will be here

6.3 Create dialog controller

We are using Angular Material’s dialog box above. Users may click the ‘Cancel’ button. We need a method for that.

  1. Open “products.controller.js”.
  2. Find “// DialogController will be here” and replace it with the following code.
// methods for dialog box
function DialogController($scope, $mdDialog) {
	$scope.cancel = function() {
		$mdDialog.cancel();
	};
}

6.4 Create “create_product” HTML form template

Our dialog box loads an HTML temlate via “templateUrl” property.

  1. Open “app” folder.
  2. Inside “app” folder, open “products” folder.
  3. Inside “products” folder, create “create_product.template.html” file.
  4. Open “create_product.template.html” file and place the following code.
<md-dialog>
    <form ng-cloak>
        
        <md-toolbar>
            <div class="md-toolbar-tools">
                <h2>Create Product</h2>
            </div>
        </md-toolbar>

        <md-dialog-content>
            <div class="md-dialog-content">

				<!-- we are using ng-model to bind this view and the 'product model -->
                <md-input-container class="md-block">
                    <label>Name</label>
                    <input ng-model="name">
                </md-input-container>

                <md-input-container class="md-block">
                    <label>Description</label>
                    <input ng-model="description">
                </md-input-container>

                <md-input-container class="md-block">
                    <label>Price</label>
                    <input ng-model="price">
                </md-input-container>

            </div>
        </md-dialog-content>

        <md-dialog-actions layout="row">
            <md-button ng-click="cancel()">Cancel</md-button>
            <md-button ng-click="createProduct()" class="md-primary">Create</md-button>
        </md-dialog-actions>
    </form>
</md-dialog>

6.5 Add “createProduct” method in controller

  1. Open “products.controller.js”.
  2. Find “// createProduct will be here” and replace it with the following code.
// create new product
$scope.createProduct = function(){

	productsFactory.createProduct($scope).then(function successCallback(response){

		// tell the user new product was created
		$scope.showToast(response.data.message);

		// refresh the list
		$scope.readProducts();

		// close dialog
		$scope.cancel();

		// remove form values
		$scope.clearProductForm();

	}, function errorCallback(response){
		$scope.showToast("Unable to create record.");
	});
}

// readOneProduct will be here

6.6 Clear form contents

We need clearProductForm to clear form values.

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

// clear variable / form values
$scope.clearProductForm = function(){
	$scope.id = "";
	$scope.name = "";
	$scope.description = "";
	$scope.price = "";
}

6.7 Show messages to user

We are using “toasts” to show messages to users.

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

// show toast message
$scope.showToast = function(message){
	$mdToast.show(
		$mdToast.simple()
			.textContent(message)
			.hideDelay(3000)
			.position("top right")
	);
}

6.8 Add “createProduct” method in factory

  1. Open “products.factory.js” file.
  2. Find “// createProduct will be here” and replace it with the following code.
// create product
factory.createProduct = function($scope){
	return $http({
		method: 'POST',
		data: {
			'name' : $scope.name,
			'description' : $scope.description,
			'price' : $scope.price,
			'category_id' : 1
		},
		url: 'http://localhost/api/product/create.php'
	});
};

// readOneProduct will be here

6.9 Output

You should see a “create” button on the upper right corner of the page. Once this button is clicked, a dialog box with a “create product” form should appear.

7.0 How To Read One Data Using AngularJS?

7.1 Put “Read One” button in products list

  1. Open “read_products.template.html” file.
  2. Find
    <!-- 'read one' button will be here -->

    and replace it with the following code.

<md-button class="md-raised md-info" ng-click="readOne(product.id)">Read One</md-button>

7.2 Show product information in dialog box

If the user click “read one” button, a dialog box will appear with the product information.

  1. Open “products.controller.js” file.
  2. Find “// readOneProduct will be here” and replace it with the following code.
// retrieve record to fill out the form
$scope.readOneProduct = function(id){

	// get product to be edited
	productsFactory.readOneProduct(id).then(function successCallback(response){

		// put the values in form
		$scope.id = response.data.id;
		$scope.name = response.data.name;
		$scope.description = response.data.description;
		$scope.price = response.data.price;

		$mdDialog.show({
			controller: DialogController,
			templateUrl: './app/products/read_one_product.template.html',
			parent: angular.element(document.body),
			clickOutsideToClose: true,
			scope: $scope,
			preserveScope: true,
			fullscreen: true
		}).then(
			function(){},

			// user clicked 'Cancel'
			function() {
				// clear modal content
				$scope.clearProductForm();
			}
		);

	}, function errorCallback(response){
		$scope.showToast("Unable to retrieve record.");
	});

}

// showUpdateProductForm will be here

7.3 Create “read_one_product.template.html” file

The dialog box need an HTML template with product information.

  1. Open “products” folder.
  2. Inside “products” folder, create “read_one_product.template.html” file and place the following code.
<md-dialog>
    <form ng-cloak>

        <!-- dialog box title -->
        <md-toolbar>
            <div class="md-toolbar-tools">
                <h2>Read One Product</h2>
            </div>
        </md-toolbar>

        <md-dialog-content>
            <div class="md-dialog-content">

                <!-- display product information -->
                <md-input-container class="md-block">
                    <label>Name</label>
                    <input ng-model="name" disabled>
                </md-input-container>

                <md-input-container class="md-block">
                    <label>Description</label>
                    <input ng-model="description" disabled>
                </md-input-container>

                <md-input-container class="md-block">
                    <label>Price</label>
                    <input ng-model="price" disabled>
                </md-input-container>

            </div>
        </md-dialog-content>

        <!-- button to close the dialog box -->
        <md-dialog-actions layout="row">
            <md-button ng-click="cancel()">Cancel</md-button>
        </md-dialog-actions>
    </form>
</md-dialog>

7.4 Add “readOneProduct” method in factory

We will get the product information from the API.

  1. Open “products.factory.js” file.
  2. Find “// readOneProduct will be here” and replace it with the following code.
// read one product
factory.readOneProduct = function(id){
	return $http({
		method: 'GET',
		url: 'http://localhost/api/product/read_one.php?id=' + id
	});
};

// updateProduct will be here

7.5 Output

You should see a “read one” button in the product list. Once user clicks this, a dialog box will appear with a product information.

8.0 How To Update Data Using AngularJS?

8.1 Put “Edit” button in products list

  1. Open “read_products.template.html” file.
  2. Find
    <!-- 'edit' button will be here -->

    and replace it with the following code.

<md-button class="md-raised md-primary" ng-click="showUpdateProductForm(product.id)">Edit</md-button>

8.2 Show editable product information in dialog box

  1. Open “products.controller.js” file.
  2. Find “// showUpdateProductForm will be here” and replace it with the following code.
// retrieve record to fill out the form
$scope.showUpdateProductForm = function(id){

	// get product to be edited
	productsFactory.readOneProduct(id).then(function successCallback(response){

		// put the values in form
		$scope.id = response.data.id;
		$scope.name = response.data.name;
		$scope.description = response.data.description;
		$scope.price = response.data.price;

		$mdDialog.show({
			controller: DialogController,
			templateUrl: './app/products/update_product.template.html',
			parent: angular.element(document.body),
			targetEvent: event,
			clickOutsideToClose: true,
			scope: $scope,
			preserveScope: true,
			fullscreen: true
		}).then(
			function(){},

			// user clicked 'Cancel'
			function() {
				// clear modal content
				$scope.clearProductForm();
			}
		);

	}, function errorCallback(response){
		$scope.showToast("Unable to retrieve record.");
	});

}

// updateProduct will be here

8.3 Create “update_product.template.html” file

The dialog box need an HTML template with product information.

  1. Open “products” folder.
  2. Inside “products” folder, create “update_product.template.html” file and place the following code.
<md-dialog>
    <form ng-cloak>

        <!-- dialog box title -->
        <md-toolbar>
            <div class="md-toolbar-tools">
                <h2>Update Product</h2>
            </div>
        </md-toolbar>

        <md-dialog-content>
            <div class="md-dialog-content">

                <!-- dialog box input fields with editable product information -->
                <md-input-container class="md-block">
                    <label>Name</label>
                    <input ng-model="name">
                </md-input-container>

                <md-input-container class="md-block">
                    <label>Description</label>
                    <input ng-model="description">
                </md-input-container>

                <md-input-container class="md-block">
                    <label>Price</label>
                    <input ng-model="price">
                </md-input-container>

            </div>
        </md-dialog-content>

        <!-- dialog box buttons -->
        <md-dialog-actions layout="row">
            <md-button ng-click="cancel()">Cancel</md-button>
            <md-button ng-click="updateProduct()" class="md-primary">Update</md-button>
        </md-dialog-actions>
    </form>
</md-dialog>

8.4 Put “updateProduct” method in controller

If the user click the “update” button in the dialog box, we will send the udpated data to the API.

  1. Open “products.controller.js” file.
  2. Find “// updateProduct will be here” and replace it with the following code.
// update product record / save changes
$scope.updateProduct = function(){

	productsFactory.updateProduct($scope).then(function successCallback(response){

		// tell the user product record was updated
		$scope.showToast(response.data.message);

		// refresh the product list
		$scope.readProducts();

		// close dialog
		$scope.cancel();

		// clear modal content
		$scope.clearProductForm();

	},
	function errorCallback(response) {
		$scope.showToast("Unable to update record.");
	});

}

// confirmDeleteProduct will be here

8.5 Put “updateProduct” method in factory

The factory will help us send data to API.

  1. Open “products.factory.js” file.
  2. Find “// updateProduct will be here” and replace it with the following code.
// update product
factory.updateProduct = function($scope){

	return $http({
		method: 'POST',
		data: {
			'id' : $scope.id,
			'name' : $scope.name,
			'description' : $scope.description,
			'price' : $scope.price,
			'category_id' : 1
		},
		url: 'http://localhost/api/product/update.php'
	});
};

// deleteProduct will be here

8.6 Output

You should see the “Edit” button in the products list. When this button is clicked, a dialog box with “udpate product” form will appear.

The form contains the editable product information.

9.0 How To Delete Data Using AngularJS?

9.1 Put “delete” button in products list

  1. Open “read_products.template.html” file.
  2. Find
    <!-- 'delete' button will be here -->

    and replace it with the following code.

<md-button class="md-raised md-danger" ng-click="confirmDeleteProduct($event, product.id)">Delete</md-button>

9.2 Ask user to confirm product deletion

  1. Open “products.controller.js” file.
  2. Find “// confirmDeleteProduct will be here” and replace it with the following code.
// cofirm product deletion
$scope.confirmDeleteProduct = function(event, id){

	// set id of record to delete
	$scope.id = id;

	// dialog settings
	var confirm = $mdDialog.confirm()
		.title('Are you sure?')
		.textContent('Product will be deleted.')
		.targetEvent(event)
		.ok('Yes')
		.cancel('No');

	// show dialog
	$mdDialog.show(confirm).then(
		// 'Yes' button
		function() {
			// if user clicked 'Yes', delete product record
			$scope.deleteProduct();
		},

		// 'No' button
		function() {
			// hide dialog
		}
	);
}

9.3 Put “deleteProduct” function in controller

If the user click the ‘Yes’ button, our app will delete the record.

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

// delete product
$scope.deleteProduct = function(){

	productsFactory.deleteProduct($scope.id).then(function successCallback(response){

		// tell the user product was deleted
		$scope.showToast(response.data.message);

		// refresh the list
		$scope.readProducts();

	}, function errorCallback(response){
		$scope.showToast("Unable to delete record.");
	});

}

// searchProducts will be here

9.4 Put “deleteProduct” function in factory

The factory will help us send data to API.

  1. Open “products.factory.js” file.
  2. Find “// deleteProduct will be here” and replace it with the following code.
// delete product
factory.deleteProduct = function(id){
	return $http({
		method: 'POST',
		data: { 'id' : id },
		url: 'http://localhost/api/product/delete.php'
	});
};

// searchProducts will be here

9.5 Output

You should see the “Delete” button in products list. When a user click this button, a dialog box will appear asking the confirmation to delete the record.

10.0 How To Search Data Using AngularJS?

This feature is part of LEVEL 2 source code. We did not use “filter” to search product records. We search the records with the help of API.

10.1 Allow users to type search keywords

  1. Open “read_products.template.html” file.
  2. Find
    <!-- 'search' bar will be here -->

    and replace it with the following code.

<!-- used for searching products in api -->
<md-input-container class="md-block m-b-0px">
	<form ng-submit="searchProducts()">
		<label>Search products...</label>
		<input ng-model="product_search_keywords">
	</form>
</md-input-container>

10.2 Add “searchProducts” function in controller

  1. Open “products.controller.js” file.
  2. Find “// searchProducts will be here” and replace it with the following code.
// search products
$scope.searchProducts = function(){

	// use products factory
	productsFactory.searchProducts($scope.product_search_keywords).then(function successCallback(response){
		$scope.products = response.data.records;
	}, function errorCallback(response){
		$scope.showToast("Unable to read record.");
	});
}

10.3 Add “searchProducts” function in factory

The factory will help us read records based on search keywords.

  1. Open “products.factory.js” file.
  2. Find “// searchProducts will be here” and replace it with the following code.
// search all products
factory.searchProducts = function(keywords){
	return $http({
		method: 'GET',
		url: 'http://localhost/api/product/search.php?s=' + keywords
	});
};

10.4 Output

You should see the “search” bar above products list. Once user type a keyword and press the “enter” key, search results must be seen.

11.0 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 products, it means your set up is correct.

12.0 Download LEVEL 1 Source Code

FEATURESLEVEL 1
Create productYES
Read productYES
Read one productYES
Update productYES
Delete productYES
Angular Material UIYES
PHP REST API source codeYES
FREE email support for 3 monthsYES
Source code updates via emailYES
Download Now

13.0 Download LEVEL 2 Source Code

FEATURESLEVEL 2
All features of LEVEL 1YES
Search productsYES
Pagination of products & search productsYES
Create categoryYES
Read categoryYES
Read one categoryYES
Update categoryYES
Delete categoryYES
Search categoriesYES
Pagination of categories & search categoriesYES
Navigation barYES
Use of AngularJS DirectivesYES
Use of AngularJS $q.all()YES
Use of AngularJS MainControllerYES
Use of Single pagination template FileYES
Use of ng-class in navigation barYES
FREE email support for 6 monthsYES
Download Now

Do you need more reasons to get it?

MORE REASONS TO DOWNLOAD THE CODEALL
Use new skills for your multiple projectsYES
Save huge amount of time learning AngularJSYES
Code examples are direct to the pointYES
Well explained and commented source codeYES
Fast and friendly email supportYES
Free source code updatesYES

14.0 What’s Next?

Learn more JavaScript programming with our Angular 2 CRUD Tutorial – Step By Step Guide!

15.0 Related Source Codes

16.0 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 mike@codeofaninja.com, 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!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. Get a FREE EBOOK as well. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

Thanks for reading our AngularJS CRUD Example with Material Design – Step by Step Guide!

Home PHP

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.

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?

Read more

display-twitter-feed-on-website-1

How To Display Twitter Feed on Website? Step By Step Guide!

display-twitter-feed-on-website-1
Before we start coding, let me ask you this: Do you really want to code this feature on your website? Or would you prefer to use a website plugin that does the trick instantly?

There is an easy way to customize & embed Twitter feed on your website. No coding required. How? Use the DSM Website Plugin! Learn how to use it from this Step by step tutorial.

Going back to coding…

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!

Read more