Skip to content

Static CV for IT Graduate built with HTML, CSS, JavaScript, jQuery, Bootstrap

Share Button

Sooner or Later each IT graduate will be looking for a IT related job… At least most of them.

 

Live Demo

sharemywe_static_cv_about_section

As a Computer Science graduate I think that each person applying for IT related job should have an online CV up and ready so when applying for an actual job, a prospective/future employers could view your resume on desktop, laptop, mobile etc.

That’s  why I’ve decided to create an example of online resume that you could use as your own, adjust  content or change styling and functionality if you wish.

Below CV is a static webpage built with HTMl, CSS, JavaScript, jQuery and Bootstrap.

CV Consist of 4 main sections : About, Website, Experience and Contact.
If you wish you can add additional question or remove it. I have applied number of comments within files so you will have no difficulties when applying changes.

 

Download

sharemywe_static_cv_contact_section

Live Demo

 

Resume consists of 3 files:

index.html

style.css

font-awesome

 

Functionalities

  • Each time you click on navigation pane item, the color will change, indicating that you’re displaying this actual section.
  • In ‘about’ section next to a job title, you’ll notice certain technologies scrolling down. It’s a nice feature that will give an idea of technologies you’re using to the people viewing your resume.

 

I won’t discuss all functionalities within this section, I will let you to download and check the resume yourself 😉

 

sharemywe_static_cv_experience_section

 

That’s all for this post. I hope You’ve enjoyed it.
If you have any questions, ideas or improvement suggestions, don’t hesitate and let me know 😉

 

Share Button

Responsive Pagination with PHP, MySQL and Bootstrap

Share Button

 

Responsive Pagination with PHP, MySQL and Bootstrap

Most of the websites deals with enormous amount of content that of course somehow must be displayed to the users. If a website would need to fetch from database and display thousands of records(images, video links etc) on one page it would not be easy to digest, especially if there would be thousands of queries at the same time. Besides, no one want to see all to content on one , endless to scroll page.

sharemyweb_php_mysql_pagination

Paging allows to display only the records required / requested by a user. So instead of putting all results on one page, the content spread over several pages. It makes it much easier to read and of course, the content is fetched from database only when user request it by clicking on appropriate page.

Download

Pagination is possible thanks to MySQL ‘LIMIT’ and ‘OFFSET’.

‘LIMIT’ clause, basically specifies the number of records to be returned. So we can for example return only records from 1-26 and no more. Or records from 1-15. Simple as that.

‘OFFSET’ clause on the other hand allows to specify from which reord we would like to start. For example, we could start from record 7 or 9 or any other record we wish.

I came across many pagination classes that sometimes were to long winded and messy.That’s why I’ve decided to write a simple php pagination class that can be understand and implemented by anyone.

Throughout the code I have implemented appropriate explanations so you’ll be able to adjust the code to your needs if needed. Also, I’ve made the pagination demo responsive, so you can test in on desktop, laptops, tables and mobile devices.

sharemyweb_php_mysql_pagination_small_screen

All you need to do is:

– Download .zip file (Download button provided below)
– Create database ‘pagination’ in MySQL
– Import pagination.sql(perhaps via phpMyAdmin)
– Change your Database Credentials in dbConfig.php
– Open pagination demo files in your browser and test it 😉

If you have already downloaded .zip, you’re ready to go.

Create MySQL database with:

CREATE DATABASE IF NOT EXISTS pagination;

When you already have your database in place, download pagination.sql via phpMyAdmin

  1. Click the name of newly crated database – > pagination
  2. Click on import to start the import process
  3. Browse for the pagination.sql and import it….. Done!!!!

sharemyweb_php_mysql_pagination_php_my_admin

 

sharemyweb_php_mysql_pagination_image_table

Change MySQL database credentials in dbConf.php file. You’ll only need to specify your database user and password. Then open the browser and open first(index.php) page.

sharemyweb_php_mysql_pagination_content

Pagination demo consists of following files:

sharemyweb_php_mysql_pagination_files_folders

 

Download

dbConf.php

This file includes all MySQL credentials necessary for database connection like. You should open the file and change DB user and password so the successful connection to MySQL database can be established. It’s purely, up to you, but I prefer to keep database credentials in separate file.

database.php

It’s a simple database class that defined method to establish MySQL connection, and fetch the data.

paination.php

This file defines the pagination class. It basically says how the pagination functionality is set up and how it should work. I’ve applied comments and explanations under each single method, so you won’t have any bigger problem with understanding.

First thing that you’ll notice are declared variables like links(first, next, previous, last), current page and so on. Same regards to the methods: There are methods that defines, previous or next page link, finding records using ‘LIMIT’ & ‘OFFSET’ clauses… simple as that.

Pagination class also consist of constructor that takes 3 arguments: current page, items/images displayed per page, total number of items. Current pages keeps track of current page(via $_GET variable), items per page allow to display only specific number of items per page and total number of items count all items in db.

Pagination class also specifies how many pages are to be displayed before and after current/active page.

<?php

/* 
    Pagination Class 1.1
    Developed by 'Kwacho', 05/2016
    info@sharemyweb.com     
*/
class Pagination extends MySQLDatabase{
 
//############################# 
//###   DECLARE VARS  ######### 
//#############################
    
    // Current page number
    public $current_page;
    
    // items displayed per page
    public $per_page;
    
    //total number of all items
    public $total_count;
    
    //number of links displayed after current page link
    public $links_after;
    
    //number of links displayed before current page link
    public $links_before;
    
    // Number of pages after a $current_page
    public $min_pages;
    
    // Number of pages before a $current_page
    public $max_pages;
    
    // First page link name
    public $first_link;
    
    // Last page link name
    public $last_link;
    
    // Next page link name
    public $next_link;
    
    // Previous page link name
    public $previous_link;
    
    
//########################################## 
//###   CONSTRUCTOR WITH DEFAULT VALUES  ###  
//##########################################
    
    public function __construct($page=1, $per_page=1, $total_count=0){
        $this->open_connection();
        
        $this->current_page = (int)$page; // current _page
        $this->per_page = (int)$per_page; // 
        $this->total_count = (int)$total_count;
        $this->links_after = 3;
        $this->links_before = 3;
        
        // Button names and custom design
        $this->first_link = '>&laquo&laquo; First';     // <<<< First
        $this->previous_link = '">&laquo; Previous';    // << Previous
        $this->next_link = '">Next &raquo;';            // Next >>
        $this->last_link = '"\">Last &raquo&raquo;';        // Last >>>>
        $this->max_pages=''; 
        $this->min_pages=''; 
    }
    
    // Return current page
    public function getPage($page){
        $this->page = $page;
        return $this->page;
    }
    
    // Return items displayed per page
    public function getPerPage(){
        $this->per_page = 4;
        return $this->per_page;
    }
    
    public function offset(){
        // Assuming 10 items per page:
        // page 1 has an offset of 0    (1-1)*10
        // page 2 has an offset of 20   (2-1)*10
        // in other words, page 2 starts with item 11        
        return ($this->current_page - 1) * $this->per_page;
    }
    
    // Check total pages of items. Total number of items divided 
    // by number of items per page
    public function total_pages(){
        return ceil($this->total_count / $this->per_page);
    }
    
    // Counts all item in databse.
    public function last_item_number(){
        return ceil($this->total_count);
    }
    
    // Previous page = $current_page - 1;
    public function previous_page(){
        return $this->current_page - 1;
    }
    
    // Next page = $current_page + 1;
    public function next_page(){
        return $this->current_page + 1;
    }

    // if previous page is > 1(not = 0) than there is a previous page
    public function has_previous_page(){
        return $this->previous_page() >= 1 ? true : false;
    }
    
    // if next page is not smaller than a total number of pages than there is a next page 
    public function has_next_page(){
        return $this->next_page() <= $this->total_pages() ? true : false;
    }
    
    // return first page link link
    public function getFirstLink(){
        return $this->first_link;
    }
    
    // return previous page link link
    public function getPreviousLink(){
        return $this->previous_link;
    }
    
    // return next page link link
    public function getNextLink(){
        return $this->next_link;
    }
    
    // return last page link link
    public function getLastLink(){
        return $this->last_link;
    }
    
    // Finds requested records of images : DESCENDING order, so the last image added will be displayed as first one
    public function findRecords($per_page, $offset){

        global $database;        
        // Finds records for the page only.
        $sql = "SELECT * FROM images ";
        $sql .= "ORDER BY id DESC ";
        $sql .= "LIMIT {$per_page} ";
        $sql .= "OFFSET {$offset}";
        return ($database->find_by_query($sql)) ? $sql : false;
    }
}

// Instantiate class
$pagination = new Pagination();

?>

painationView.php

Display the pagination links utilizing of already created methods in pagination class(pagination.php). I have applied plenty of comments in this file so you’ll have a good idea of what’s going on and how to use it. Some people put all the paging links into one function and display it, but I preffer to give each link an independent freedom so they can be called separately if needed.

<?php 

/*
    PAGINATION LINKS / BUTTONS DISPLAY
*/

/** Defines number of pages before & after current page /active 
    For example if $pagination->links_after is set to 3, only 3 pages after current page will be available....
    You can change it if Pagination class if you wish
*/
$min = max($page - $pagination->links_before, 1); // there are no pages < 1
$max = min($page + $pagination->links_after, $pagination->total_pages());

echo "<div class='pagination' id='paginationHolder'>
        <div class='bs-example' id='paginationNav'>
            <ul class='pagination paginationList'>";

    if($pagination->total_pages() > 1) {
        
        /*##############################################
        ###          FIRST PAGE LINK / BUTTON        ###
        ##############################################*/
        if($pagination->has_previous_page()){
            echo "<li><a class='pagination_links controLinks' id='first_link' href=index.php?page=1";
        } else {
            echo "<li><a class='pagination_links controLinks disabledLink' id='first_link' disabled ";
        }
            echo $pagination->getFirstLink() ."</a></li> ";
        
        
        /*##############################################
        ###       PREVIOUS PAGE LINK / BUTTON        ###
        ##############################################*/  
        
       if($pagination->has_previous_page()){
        echo "<li><a class='pagination_links controLinks' id='previous_link' href=\"index.php?page=";
        } else {
           echo "<li><a class='pagination_links controLinks disabledLink' id='previous_link' disabled";
        }
        echo $pagination->previous_page();
        echo $pagination->getPreviousLink() ."</a></li> ";
        
        
        
        /*##############################################
        ###            ALL PAGES LINKS               ###
        ##############################################*/
        for($i = $min; $i <= $max; ++$i) {

                echo "<li><a";
if( $i==$page ? $idStyleName='selected' : $idStyleName='regularLink');
                    echo " class='pagination_links' id='{$idStyleName}' href=\"index.php?page={$i}\">{$i}</a></li> ";
        }
        
        /*##############################################
        ###          NEXT PAGE LINK / BUTTON         ###
        ##############################################*/
        if($pagination->has_next_page()){
            
            echo "<li><a class='pagination_links controLinks' id='next_link' href=\"index.php?page="; 
            
        } else {  
            echo "<li><a class='pagination_links controLinks disabledLink' id='next_link' disabled "; 
        }   
            echo $pagination->next_page();
            echo $pagination->getNextLink() ."</a></li> ";
        
        
        /*##############################################
        ###          LAST PAGE LINK / BUTTON         ###
        ##############################################*/
        if($pagination->has_next_page()){
            echo "<li><a class='pagination_links controLinks' id='last_link' href=\"index.php?page=";
        }else{
            echo "<li><a class='pagination_links controLinks disabledLink' id='last_link' disabled";
            }
            echo $pagination->total_pages();
            echo $pagination->getLastLink() ."</a></li> ";      
    }

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

?>

sharemyweb_php_mysql_pagination_content_2

index.php

File that is being read once you access pagination demo files and folders. This files request all other files and is the only file that a user should interact with. index.php. Requests pagination class, sets current page with $_GET[], create an instance of pagination class and display content(images)

<?php
    require_once("header.php");
?>
<body>
<?php

    // Require database
    require_once("database.php");
    // Require pagination class
    require_once("pagination.php");
    
    // Sets the current page for Pagination - Get hte page from $_GET global variable
    $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;

    // Create new instance of Pagination class with arguments: current page, items per pages and count all items
    $pagination = new Pagination($pagination->getPage($page), $pagination->getPerPage(), $database->num_rows());

    // Find all images according to pagination criterias- items displayed per page and offset
    $images = $database->find_by_query($pagination->findRecords($pagination->getPerPage($page), $pagination->offset()));
 ?>
    
    <div class='row' style='margin: auto; text-align:center;'>
        <div class="span9">
             <a href='http://www.sharemyweb.com' target="_blank"><img class="img-responsive" style='width:400px; margin:0 auto;' alt="ShareMyweb_Logo" src="http://sharemyweb.com/wp-content/uploads/2016/01/Demo_site_logo.png"></a>
        </div>
        <h2 style='text-align:center;'>PHP, MySQL Responsive Pagination</h2>
    <hr>
    </div>
    
    <!-- Display images-->
    <div class='container' style='width:auto; text-align:center;'>
    <?php 
        // foreach image.... display image
        foreach($images as $image){
            echo "<img clas='img display_images' src='images/{$image['image_name']}' alt='{$image['image_desc']}'><br />";          
        }
    ?>
    </div>
    
<?php 
    //Display Pagination
    require_once("paginationView.php");
    // Display footer
    require_once("footer.php");
?>

 

Download

header and footer

I believe that these two sections don’tt need a bigger explanation so I’ll just take few seconds to describe header briefly. This file defines bootstrap links and scripts, website title, css file and small browser icon that appears on your browser tab(it just looks nice).

Images folder

I have included few custom images so you see how the pagination works in the demo. You can change images as you wish, same as you can use this demo as you like.

That’s all. Now, download the pagination demo, play with it and change it as much as you wish. If you have any questions, ideas for improvements, don’t hesitate let me know.

Share Button

Ajax Shopping Cart, PHP, jQuery and Bootstrap

Share Button

Ajax Shopping Cart, PHP, jQuery and Bootstrap

ajax_sharemyweb_shopping_cart_top

 

Download

Shopping cart applications are an integral part of e-commerce websites all over the internet, that drives the businesses profits, allowing for a wider range of customers. Most of the shopping cart out there, rely strictly on PHP, which seems to power most of the web. When I think of PHP I also think of page refresh on each single PHP request. Don’t get me wrong, but sometimes it may be a bit annoying when the page gets refresh all the time. AJAX allows to grab a data/content whatever… with no page refresh, so we can actually update the relevant part of page in a smooth way. Not mentioning that AJAX is FASTER indeed as it doesn’t need to start whole page over and over again and the changes or content requested shows up immediately.

ajax_sharemyweb_item_added

Today I present you and AJAX shopping cart, that comes with a nice functionalities + some extra to make it even better.

The Ajax shopping cart is made of following:  HTML, CSS, jQuery(Ajax), PHP, MySQL, Bootstrap

Let’s start:

First thing is to create a MySQL database, which will store all information about items like: item_id, item_name, image corresponding to specific item and also item category, which will be useful when we would like to display only items from specific category. Firstly, you will need to create a MySQL database, which I have called ‘shoppingCartDemo‘. In Download files(.zip) I have included a shoppingCartDemo.sql file, which  holds of 2 MySQL tables for shopping items and menu items, which are already populated with sample data that you can work with. You can import the file via phpMyAdmin or similar.

Before you import the shoppingCartDemo.sql file, create a shoppingCartDemo database. You can do it with following:

CREATE DATABASE IF NOT EXISTS shoppingCartDemo;

After you have a database in place, you can import shoppingCartDemo.sql

If you’re using phpMyAdmin:

  1. Click the name of newly crated database – > shoppingCartDemo
  2. Click on import to start the import process
  3. Browse for the shoppingCartDemo.sql and import it….. Done!!!!

 

import_SQL_file_phpMYAdmin

 

Both tables I have in my database looks like this:

shopping_items

items_table

 

menuItems

item_menu_table

 

Shopping cart consists of following files:

ajax_shopping_cart_files

All files comes with comments so it will be easy for you to alter them if needed.

I have arranged all above files and folders up to my preference but feel free to change it if you wish.

 

Download

 

dbConf.php

This file includes all MySQL credentials necessary for database connection like: database name, user, password and server. It’s purely up to you, but I always keep those credentials in separate file, which is later included by other file in order to make a database connection.

<?php

/**
 * The base configurations of MySQL settings.
 *  
 *  Database Constraints
 *  If constraints are defined : CONNECT if NOT defined :  DEFINE CONSTANTS
 *
 *  FILL BELOW VALUES : DB_SERVER       localhost OR 127.0.0.1
 *                      DB_NAME         your database name  
 *                      DB_USER         database username
 *                      DB_PASSWORD     database password
*/


/** MySQL Server / hostname .... optionally 127.0.0.1*/
defined("DB_SERVER") ? null : define("DB_SERVER", "localhost");

/** MySQL Database to be Connect to*/
defined("DB_NAME") ? null: define("DB_NAME", "shoppingCartDemo");

/** MySQL database username */
defined("DB_USER") ? null : define ("DB_USER", "Type your db user here...");

/** MySQL database password */
defined("DB_PASSWORD") ? null : define ("DB_PASSWORD", "type your db password here...");

/** Database Charset to use in creating database tables. */
defined('DB_CHARSET') ? null : define('DB_CHARSET', 'utf8');


?>

 

database.php

This is a simple MySQL database Class, that holds of methods that make the database connection, query database for content etc. Nothing difficult at all. I’d rather keep those in separate place so it’s much easier to handle MySQL calls and the code will look much neater.

<?php

/* This file contains methods to connect to DB, search for elements etc.....*/

/* Request MySQL Conf file with credentials */    
require_once("dbConf.php");

class MySQLDatabase
{
    private $connection;
    public $last_query;
     /*Table name*/
    private $dbMenuItems="menuItems";
    public $imageCategories = array('Funny','Facebook','Ofensive','Animals','Sexy');
    
    // Constructor
    function __construct(){
        $this->open_connection();
    }
    
    // Open MySQL Connection
    public function open_connection(){
        try{
            $this->connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
        }catch(Exception $except){
            die("Unable to connect to Database");
        }
    }
    
    // Close MySQL Connection
    public function close_connection(){
        if(isset($this->connection)){
            $this->connection->close();
            unset($this->connection);
        }
    }
    
    // Run MySQL Query
    public function query($sql){
        $this->last_query = $sql;
        $result = mysqli_query($this->connection, $sql);
        $this->confirm_query($result); 
        return $result;
    }
    
    // Confirm MySQL Query
    private function confirm_query($result){
        if(!$result){
            $output = "Database query failed: " . mysqli_error($this->connection) . "<br />";
            $output .= "Last MySQL Query: " . $this->last_query;
           die($output);  
        }
    }
   
    // Fetch array and return results
    public function fetch_array($result){
        return mysqli_fetch_array($result);
    }
    
    public function find_by_query($query=""){
        $result = $this->query($query);
        $arrayWithData = array();
        while($row = $this->fetch_array($result)){
            $arrayWithData[]=$row;
        }
        $this->close_connection();
        return $arrayWithData;   
    }
        
        /* Run query, find results, save results to $object_array, return $object_array */
    public function findMenuItem(){
        global $database;
        $result = $database->query("SELECT * FROM ".$this->dbMenuItems." ORDER BY id ASC");
        $object_array = array();
        /* Save results to object array */
        while($row = $database->fetch_array($result)){
            $object_array[]=$row;
        }
        /* Return object array*/
        return $object_array;          
        /* Close MySQL connection */
        $this->close_connection();
    }    
    
    /** Returns upload Categories*/
    public function getFileCategories(){
        $categories = $this->imageCategories;
        return $categories;
    }      
}

// Instantiate class - creates and Instance of the class under the $database var name
$database = new MySQLDatabase();

?>

 

header.php

Holds of… what header usually holds 😀 Apart from including .css file and starting php session, header also includes bootstrap file links and of course jQuery. Without jQuery script all the magic would not happen. header.php will be included by index.php file. I have decided to open a session in the header so it won’t be necessary to open in in all other files, as we’ll be saving shopping items in session variable.

<!DOCTYPE html>

<html>
    
<head>
    
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--    Page Title-->
<title>ShareMyWeb Ajax Shopping Cart : http://www.sharemyweb.com </title>    

<!-- jQuery: Latest minified jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<!-- BOOTSTRAP: Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href="bootstrap-3.3.6/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> 
<!-- BOOTSTRAP: Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    
<!-- Main jQuery / AJAX script -->
<script type="text/javascript" src="js/mainJSscript.js"></script>
    
<!--Logo/favicon/icon-->
<link rel="shortcut icon" type="image/x-icon" href="http://sharemyweb.com/wp-content/uploads/2016/01/ShareMyWeb_Favicon.png" />    

<!--Main CSS-->
<link href="style/style.css" rel="stylesheet" type="text/css">

</head>
    
<?php
/* Start session in a header so you don't need to start it on each single page....maybe on some :p*/
if(session_status()==PHP_SESSION_NONE){session_start();}
/* Require / request database file with methods and actions to be performed */
require_once("database.php");    
?>

 

footer.php

Same as header.php above, footer.php will be included by a index.php file. It’s just a sample footer that does nothing in particular.

 

index.php

ajax_sharemyweb_general

 

This file fetches available products from database and lists them. As it includes the header.php, which includes of database.php file, we can use ready methods to get our items:

$items = $database->find_by_query("SELECT * FROM shopping_items");    

Above fetches all from shopping_items  database so we can foreach() through and display it any way we want. On top of the files I have also included some extras so the AJAX shopping application looks a bit nicer: navigation_bar.php contains of navigation menu, that you can see in the screenshot below. Currently it contains only 3 categories(T-shirt, Jumper and Jacket). You can add any categories you want. All you need to do is to go to database table menuItems  and add additional category. navigation_bar.php will automatically detect categories and display them. Also make sure that at least one items category  row form shopping includes the category placed in menuItems as otherwise no items will be displayed. Another extra I have added is a bootstrap carousel/slider -> carousel.php. It gives a nice look to the webpage and can serve for advertising purposes.

When an item is added to the cart the shopping cart bar count is being updated in a real time:

ajax_sharemyweb_item_count_update

Entire file below:

<?php 
    /* Get header */
    require_once("header.php");
?>
<body>
         
    <?php
        /* Get Navigation Bar */
        require_once('navigation_bar.php');
        /* Get Carousel/slider */
        require_once("carousel.php");
    ?>
    
    <div class='shopping_cart_info_holder'>
        <div class="col-xs-12">
            <a href="#" class="shopping_cart_info" title="Shopping cart item total">             
                <i class='glyphicon glyphicon-shopping-cart' style='color:#008cba; font-size:25px;'></i>            
                <span id='items_in_shopping_cart' style='color:#ff5500; font-size:25px;'>
                    <?php 
                        /* If there are items in the basket display total of items, else display 'empty'*/
                        if(isset($_SESSION["items"])){   
                            if(count($_SESSION["items"]) > 0){
                                echo count($_SESSION["items"]);
                            }else{
                                echo "empty";
                            }
                        }else{
                            echo "empty";
                        }
                    ?>
                </span>
            </a>
        </div>
    </div>

    <!-- Holds shopping cart info with selected items -->
    <div class="shopping_cart_holder">
        <a href="#" class="close_shopping_cart_holder" >Close Cart</a>
        <h2>Shopping Cart</h2>
        <div id="shopping_cart_output">
        </div>
    </div>
    
    <!--    Display Item here-->
    <div class="item_display_holder"></div>

    <!-- Display info about cart update in the middle of the screen -->
    <div id='cart_update_info'></div>

    <?php    
        /* FETCH ITEMS ACCORDING TO CATEGORIES CHOSEN BY USER */
        if(isset($_GET['menu'])){
            $menuCategory = $_GET['menu'];        
            /* If you want to display all items click on ShareMyWeb Logo */
            if($menuCategory =="main"){
                $items = $database->find_by_query("SELECT * FROM shopping_items");    
            /* Categories accordingly */
            }else{            
                $items = $database->find_by_query("SELECT * FROM shopping_items WHERE category='{$menuCategory}'");    
            }
        }else{
            $items = $database->find_by_query("SELECT * FROM shopping_items");    
        }
    ?>  
    
    <div class='container' style='padding:10px;'>
    <!--Display Items in the List -->
        <ul class="list_of_items">
            <?php foreach($items as $item) { ?>
                <div class="col-xs-12 col-sm-4">    
                    <li>                                      
                        <form class="item_form">                            
                            <div class='item_disp_img_holder'>                                            
                                <img class="item_disp_image" src="images/<?php echo $item["item_image"]; ?>" item_id="<?php echo $item["item_id"]; ?>" alt="<?php echo $item["item_name"]; ?>">
                                <div class='item_title_holder'>
    <span class='item_disp_title'><?php echo $item["item_name"]; ?></span>
                                </div>
                            </div>                    
                            <div style='width:235px; text-align:center; margin:0 auto;'>
                                <span style='font-size:25px;'><?php echo "£".$item["item_price"]; ?></span>
                            </div>
                            <div class="item_disp_values">
                                <div>Quantity:
                                    <select name="item_qty">
                                        <?php
                                            // Choose itemquantity
                                            $maxQty=5;
                                            for($i=1;$i<=$maxQty;$i++){
                                                echo "<option value='{$i}'>$i</option>";
                                            }
                                        ?>
                                    </select>
                                </div>
                                <div>Size:
                                    <select name="item_size">
                                        <?php 
                                            /* Specify size option in array below */
                                            $options=array("XS","S","M","XL","XXL");
                                            foreach($options as $option){
                                                echo "<option value='{$option}'>$option</option>";
                                            }
                                        ?>
                                    </select>
                                </div>
                                <input name="item_id" type="hidden" value="<?php echo $item["item_id"]; ?>">
                                <button class='add_item_to_cart' type="submit">Add Item</button>
                            </div>
                        </form>
                    </li>
                </div>
            <?php } ?>
        </ul>
    </div>
     <div class="push"></div>
    
<!--  Get footer-->
    <?php
        require_once("footer.php");
    ?>

 

shoppingCartData.php

ajax_sharemyweb_cart_content

 

This file consists of shopping cart. After item is added to the cart, the cart is being updated. All the data in the file is being updated via AJAX call so there’s no need for a page refresh.

When we click on the total item count bar, the data from shoppingCartData.php will be loaded and items display accordingly. I did not go to crazy with shopping cart options so it has the basic functionalities in the form of: update cart in a real time, open and close cart, update item quantity, remove item and go to Checkout.

 

Download

Once the item is added to the cart by clicking on ‘Add item’ button in index.php, the data is being sent via AJAX to shoppingCartData.php, processed there and returned. Simple as that. As we’re dealing with PHP(server site) and JS(client site), we need some alternative to transmit/return the data, which comes in the solution of JSON. Simply speaking JSON returns transmitted data in a PHP format. Sample JSON

exit(json_encode(array('items_in_cart'=>count($_SESSION['items']))));

 

All item added to the shopping cart will be stored in $_SESSION[‘items’] so it’s accessible in other files as well.

All shoppingCartData.php file below:

<?php

/* If session is not started, start session */
if(session_status()==PHP_SESSION_NONE){session_start();}
require_once("database.php");  // request database connection with its objects 

if(isset($_POST["item_id"]) && isset($_POST['item_qty'])){
    /* Get $_POST data and place it in array */
    $added_item["item_id"]=$_POST['item_id'];
    $added_item["item_qty"]=$_POST['item_qty'];
    $added_item["item_size"]=$_POST['item_size'];

    /* Fetch all items from database that matches $_POST['item_id'] 
        Limit 1 at the end so only one item is fetched. */
    $items = $database->find_by_query("SELECT * FROM shopping_items WHERE item_id='{$added_item["item_id"]}' LIMIT 1");
    
    /* Foreach item -> Remaining data about items fetched from database */
    foreach($items as $item){
        $added_item["item_name"] = $item['item_name']; 
        $added_item["item_price"] = $item['item_price'];
        $added_item["item_image"] = $item['item_image'];
        
        /* Update item session array with newly added items - items that already exist in the basket will be overwritten */
        $_SESSION["items"][$added_item['item_id']] = $added_item;        
    }    
    /* Calculate number of items in cart and output it in json format */
    exit(json_encode(array('items_in_cart'=>count($_SESSION['items']))));  
    
}
/* Display aded products in the shopping cart */
if(isset($_POST["load_cart_items"])){

    /* If item session is already set and if there are any items added to the session */
    if(isset($_SESSION["items"]) && count($_SESSION["items"])>0){
    ?>
        <table class='table'> <!--Start table that will holds all data in the shopping cart --> 
        <?php
        $total=0; // define total so the script won't throw silly error of a type 'Undefined variable: total in....'
        
        /* Loop through item session array and display data */        
        foreach($_SESSION["items"] as $item){         
        ?>            
            <tr class='itemInCardRow'>            
                <td class='itemInCartDisplay'>
                    <img class='img-responsive item_disp_image' style='max-width:80px; float:left;' src="images/<?php echo $item["item_image"]; ?>">
                </td>

                <td class='itemInCartDisplay'>
                    <?php echo $item["item_name"] .", size ". $item["item_size"]; ?>            
                </td>

                <td class='itemInCartDisplay'>
                    <a href='#' class='subtruct_itm_qty quantity_change' item_id="<?php echo $item["item_id"]; ?>">-</a>  
                        <?php echo "<span class='quantity'>Qty ".$item["item_qty"]."</span>"; ?>    
                    <a href='#' class='add_itm_qty quantity_change' item_id="<?php echo $item["item_id"]; ?>">+</a>        
                </td>

                <td class='itemInCartDisplay'>
                    <?php echo "£".sprintf("%.2f", ($item["item_price"] * $item["item_qty"])); ?>
                </td>
                <td class='itemInCartDisplay'>
                    <a href="#" class="remove_item_from_cart" item_id="<?php echo $item["item_id"]; ?>">x</a>            
                </td>            
            </tr>
            
        <?php
            /* Calculate Total */
            $total += ($item["item_price"] * $item["item_qty"]);            
            }  // Close foreach loop
        ?>
            <!-- This part displays Checkout button and price total -->
            <tr>                 
                <td class='itemInCartDisplay' colspan='4'>
                    <div>
                        <a href='checkOut.php' title="Review Cart and Check-Out"><button type="button" class="btn checkoutButton">CHECKOUT</button></a>
<!--                        <a class="checkoutButton" href="view_cart.php" CHECKOUT</a>            -->
                    </div>
                </td>                
                 <td class='itemInCartDisplay' style='text-align:right;'>
                    <div class="cart-products-total">                        
                        <span>Total : <span style='font-size:20px; color:#008cba;'></span>
                            <?php
                                // Return a total price with 2 decimals 
                                echo "£".sprintf("%.2f",$total); 
                            ?>
                        </span>
                    </div>
                </td>
            </tr>
        </table>
    
    <?php 
       
    }else{
        /*  Information about empty shopping cart  - exit() function prints a message and exits current script
            Can be used as die() */
        exit("Your have no items in your Shopping Cart");
    }    
}

/* Add item quantity - Allow maximum 5 of each item to be added  */
if(isset($_GET["add_itm_qty"]) && isset($_SESSION["items"])){
    if(isset($_SESSION['items'][$_GET["add_itm_qty"]])){
        if($_SESSION['items'][$_GET["add_itm_qty"]]["item_qty"] <= 4){
            $_SESSION['items'][$_GET["add_itm_qty"]]["item_qty"]+=1;
        }else{
            $_SESSION['items'][$_GET["add_itm_qty"]]["item_qty"]=5;    
        }          
    }        
    unset($_GET["add_itm_qty"]);
    exit(json_encode(array('items_in_cart'=>count($_SESSION['items']),(array('all_items'=>$_SESSION["items"])))));     
}

/* Subtract item quantity - deduct qty ONLY if item_qty is NOT smaller than 0  */
if(isset($_GET["subtruct_itm_qty"]) && isset($_SESSION["items"])){
    if(isset($_SESSION['items'][$_GET["subtruct_itm_qty"]])){
        if($_SESSION['items'][$_GET["subtruct_itm_qty"]]["item_qty"] >= 2){
            $_SESSION['items'][$_GET["subtruct_itm_qty"]]["item_qty"]-=1;    
        }else{
            $_SESSION['items'][$_GET["subtruct_itm_qty"]]["item_qty"]=1;    
        }        
    }
    unset($_GET["subtruct_itm_qty"]);
    /* Get item quantity and output it in json format */
    exit(json_encode((array('item_qty'=>$_SESSION["items"]))));     
}

/* Remove item from shopping cart */
if(isset($_GET["remove_item_from_cart"]) && isset($_SESSION["items"])){
    $item_id = $_GET["remove_item_from_cart"];
    /* Check if item is ina item session array */
    if(isset($_SESSION["items"][$item_id])){
        unset($_SESSION["items"][$item_id]);  // Remove/unset item
    }
    /* Calculate total number of items in cart and output it in json format */
    exit(json_encode(array('items_in_cart'=>count($_SESSION['items']))));    
}

 

js/mainJSscript.php

This is the script that contains of jQuery functions including AJAX requests. Below is the simple AJAX requests. It contains the webpage to which we’re sending the request, request method, data we’re passing, and how we could like the data to be organized.

   /* Action on form submit */
    $(".item_form").submit(function(e){
        var form_data = $(this).serialize();            
        /* AJAX request  - shoppingCartData.php */
        $.ajax({
            url: "shoppingCartData.php",
            type: "POST",
            dataType:"json", 
            data: form_data
        }).done(function(data){ //if AJAX request if succesfull .....
            var totalItemInCart = $("#items_in_shopping_cart").html(data.items_in_cart); // get Json data                   
            var new_item_qty = $("#items_in_shopping_cart").html(data.all_items); // get Json data                   
            /* Empty the update info bar before calling it. Otherwise appended content will duplicate. */
            $('#cart_update_info').empty();
            /* append data/info to cart_update_info bar */
            $("#cart_update_info").append("<div id='new_item_added'><i class='glyphicon glyphicon-ok' style='color:green;'></i> Item added to the cart</div>").fadeIn('fast').delay(2000).fadeOut('fast');
            /* If shopping cart is still open, items will appear on it at the same time of adding them */
            if($(".shopping_cart_holder").css("display") == "block"){ // Check if shopping cart is open 
                $(".shopping_cart_info").click( "click" );  // update cart on event
            }
        })
        e.preventDefault();
    });

This script also contains of functions that update cart in a real time wit data, open and close cart, update item quantity, remove items etc. I have left 1 or 2 functionalities that you can if you feel like(commented out at the bottom of the script). All functions are more less described with some comments, do you won’t be lost 😉

The jQuery/AJAX Script below(mainJSscript.js):

$(document).ready(function(){    
    
    /* Action on form submit */
    $(".item_form").submit(function(e){
        var form_data = $(this).serialize();            
        /* AJAX request  - shoppingCartData.php */
        $.ajax({
            url: "shoppingCartData.php",
            type: "POST",
            dataType:"json", 
            data: form_data
        }).done(function(data){ //if AJAX request if succesfull .....
            var totalItemInCart = $("#items_in_shopping_cart").html(data.items_in_cart); // get Json data                   
            var new_item_qty = $("#items_in_shopping_cart").html(data.all_items); // get Json data                   
            /* Empty the update info bar before calling it. Otherwise appended content will duplicate. */
            $('#cart_update_info').empty();
            /* append data/info to cart_update_info bar */
            $("#cart_update_info").append("<div id='new_item_added'><i class='glyphicon glyphicon-ok' style='color:green;'></i> Item added to the cart</div>").fadeIn('fast').delay(2000).fadeOut('fast');
            /* If shopping cart is still open, items will appear on it at the same time of adding them */
            if($(".shopping_cart_holder").css("display") == "block"){ // Check if shopping cart is open 
                $(".shopping_cart_info").click( "click" );  // update cart on event
            }
        })
        e.preventDefault();
    });
    
    /* Display shopping cart content when clicking on shopping_cart_info bar */
    $(".shopping_cart_info").click(function(e) {
        e.preventDefault();         
        $(".shopping_cart_holder").fadeIn(); // how to cart displays - you can change to any event you wish.
        /* Ajax call for shoppingCartData.php if $_POST['load_cart_items'] */
        $("#shopping_cart_output" ).load( "shoppingCartData.php", {"load_cart_items":"true"});
    });    
    
    /* Close Cart by clicking 'close' button */
    $( ".close_shopping_cart_holder").click(function(e){
        e.preventDefault(); 
        $(".shopping_cart_holder").fadeOut(500); // close cart of fadeOut ... or any event you wish 
    });
    
    //Remove items from cart
    $("#shopping_cart_output").on('click', 'a.remove_item_from_cart', function(e) {
        e.preventDefault(); 
        var item_id = $(this).attr("item_id"); // get item id        
        /* This part make sure tha the removed item disappears from shopping cart and is being removed */
        /* json gets the item_id */
        $.getJSON( "shoppingCartData.php", {"remove_item_from_cart":item_id} , function(data){ //get Item id
            $("#items_in_shopping_cart").html(data.items_in_cart); //update Item count in cart-info bar
            // update shopping cart content
            $(".shopping_cart_info").trigger( "click" ); 
        });
    });  

    /* Change item quantity - ADD */
    $("#shopping_cart_output").on("click", "a.add_itm_qty", function(e){
        e.preventDefault(); 
        var item_id = $(this).attr("item_id");   
        $.getJSON( "shoppingCartData.php", {"add_itm_qty":item_id} , function(data){ 
            // update specific item quantity on event
            $(".shopping_cart_info").click(); 
        });
    }); 

    /* Change item quantity - SUBTRUCT */
     $("#shopping_cart_output").on("click", "a.subtruct_itm_qty", function(e){
        e.preventDefault(); 
        var item_id = $(this).attr("item_id");   
        $.getJSON( "shoppingCartData.php", {"subtruct_itm_qty":item_id} , function(data){ 
            // update specific item quantity on event
            $(".shopping_cart_info").click(); 
        });
    }); 
        
    /* Display image on click */
    $(".item_disp_image").click(function(e){
        e.preventDefault(); 
        var item_id = $(this).attr("item_id");
        $.post('displayItem.php',{item_id: item_id}, function(data) { // send post data to displayItem.php
            var item_display_id = $(".item_display_holder").html(data); // update the data in .item_displa_holder
        });
    }); 
    /* Close image on click */
    $(".item_display_holder").on("click",".close_image", function(e){
        e.preventDefault();
        $("#item_display").hide();
    });    
    
    /* Show image title on item hover */
    $('.item_disp_img_holder').hover( function() {
        $(this).find('.item_disp_title').css("display","block","width","inherit");
    }, function() {
        $(this).find('.item_disp_title').fadeOut(200);
    });
        
    /*   ADDITIONAL OPTIONS YOU COULD USE    */
        
    /* Close Cart when mouse leaves shopping_cart_holder area - ADDITIONAL OPTION */
//    $( ".shopping_cart_holder").on("mouseleave",function(e){ // how to cart closes - you can change to any event you wish.
//        e.preventDefault();            
//        $(".shopping_cart_holder").fadeOut();
//    });    
    
    // Enlarge image on hoover 
//    $('.item_disp_image').hover(function() {
//    $(this).css("cursor", "pointer");  // Shows a pointer type
//    $(this).animate({
//        width: "100%",
//        height: "100%"
//    }, 'fast');

    // Go back to default image size
//    }, function() {
//        $(this).animate({
//            width: "80%"
//        }, 'fast');
//    });
     
});

 

displayItem.php

This checks for image of item being clicked and returns it. After the image is returned we can do anything we want with it. I went simple way and just displayed the image(adding small image enlarge with css). You can take it even further if you want and display item description or create simple gallery…. whatever you wish.

 

ajax_sharemyweb_image_enlarge

 

checkOut.php

Takes you to check-out page, displaying items in the cart and giving two additional options: continue shopping or pay for items.

ajax_sharemyweb_checkout

 

Images

I have included some images in the image/ folder from publicly available source – asos.com, so you don’t need to waste time to put your own images.

 

That’s all. Now, download the AJAX cart application and play with it and change it as much as you wish. If you have any questions or ideas, don’t hesitate let me know. Thx

 

Download

Share Button

Create Sample Demo Pages With Download Button

Share Button

Sample demo pages with PHP and Download Button

This is a quick tutorial for creating a sample demo pages for your website. If you want to share your projects and demos with your website visitors you should be able to present a live demo of your code and allow user to download it(Possibly for FREE).
If that’s what you would like to achieve… This post is perfect for you!

Let’s start without further postponement.

Below is a simple demo pages file system that can serve to you as a demo sample

Live_demo_filesystem

 

demo_page_example

 

Download

 

Assets hold of all live demo pages directories and a singe index.php file which will redirect every page request which does not specify which specific project user want to view.

defaultStyles.css specifies default styles for all demo projects. Default styles mostly apply to default elements of the demo pages like: top navigation bar, footer, download button.

downloadButton.php …. as a name specifies is as download button for a project etc.

Below is a simple function that accepts 2 arguments: script location to be downloaded by user and a download button text. It’s a default button which has the same css style for all other demo projects.

<?php
/* Download button function with 2 arguments: script location to be downloaded and button text */
function dispDownlButton($scriptLink,$downloadMsg){ ?>

    <div class="dowloadButtonHolder">
        <div class="row">
            <a class='downloadButton' href="<?php echo $scriptLink; ?>"><?php echo $downloadMsg; ?></a>
        </div>
    </div>

<?php } ?>

 

footer.php is a default footer for all demo pages. It’s just a footer example so fell free to add any content you want to check how it works.

live_demo_footer

 

header.php is a default header for all demo pages. Note that the head section of the demo page is not closed as it will be continued for each demo project separately.

live_demo_header

 

helperFunctions.php contains of all php functions that will come in handy for demo pages. I’ve added only 2 functions but if you fell that your demo pages would benefit from more functions, don’t wait and simply add them. getPageTitle($pageTitle) accepts one argument(page title) and echos it closed in html title tag.

Second function simply creates a redirection link with a custom link text.

<?php

    /* PHP Helper functions */

    /* Get title for page */
    function getPageTitle($pageTitle){
        echo"<title>{$pageTitle}</title>";        
    }

    /* Create a redirection link with a custom link text */
    function redirectLink($url,$linkMsg){        
        $link = "http://www.{$url}";
        echo "<span><a id='pageTitleDemo' href='{$link}' target='_blank'>".$linkMsg."</a></span>";
    }

?>

 

topNavBar.php contains of default navigation bar. In this demo example it only contains an image but you can modify it to navigation menu or something else if you wish.

live_demo_head

 

SIMPLE DEMO PAGE:

Below is a simple demo page files. Each demo page prior this example should be kept in separate directory/folder.

 

This simple example consists of 4 files:

demoPage.html

index.php

header.php

styles.css

index.php is the main file of each single demo page which specify all files to be requested in order to run a demo page. Comments were applied throughout the code so you won’t have any difficulties understanding it.

demo_page_index

demoPage.html is the actual demo project code. This file will be required by a main index.php file.

main_demo_page_content

header.php is a continuation of default header.php. It not only requires a default header but also sets a page title for this actual demo page and adds additional scripts, styles etc. if needed.

demo_page_header

styles.css contains of additional styles for this specific demo page.

Download the code, read through comments, play with it and set up your own demo pages.

You can check for sample demo pages under below links:

Sample Demo 1
Sample Demo 2

Download

 

Share Button

jQuery Redirection With Countdown – Live Demo

Share Button

Sometimes we want to redirect a user to a specific page within a certain amount of time.
It’s good and clear if we let the user know when exactly redirection will start.
jQuery comes with a perfect solution that can make it happen.

Below is a screenshot of complete jQuery redirection example:

 

jQuery_redirection_with_countdown

 

Live Demo

 

Below is a jQuery script that let us to redirect page after a countdown and display necessary text.
I’ve applied appropriate comments throughout the script for better understanding.

/* Countdown seconds */
var count = 5;
/* Website to redirect */
var url = "http://www.sharemyweb.com";
/* Call function at specific intervals */
var countdown = setInterval(function() { 
    /* Display Countdown with txt */
    $('#displayTimer').text("Redirection in: " + count-- + " seconds");
    /* If count is smaller than 0 ...*/
    if (count < 0) {
        $('#displayTimer').text("Redirecting now....");
        /* Clear timer set with setInterval */
        clearInterval(countdown);
        /* Redirect */
        $(location).attr("href", url);
   } 
    // milliseconds
}, 1000);

 

You can set your own countdown time redirection link. The only thing you need to do is to set first variables on the top of the script: url and countdown.

 

Just before redirection after a countdown is completed a counter will change into redirection text like below:

 

 

 

Demo version of he code contains two files. First one is the script above and second one is index.html that contains all markup, styles etc.:

<!DOCTYPE html>

<html>    
    
    <head>        
        <title>jQuery Redirection With Time Delay</title>        
        <meta charset="UTF-8">
        <meta content="width=device-width, initial-scale=1.0" name="viewport">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">           </script>        
        <style>
            #timeCounterHolder{
                margin:0 auto;    
            }
            #displayTimer{
                color:#666;
                font-size:50px;
                text-align:center;
            }
        </style>        
    </head>

<body>

    <div id='timeCounterHolder'>
        <div id='row'>
            <p id='displayTimer'></p>
        </div>            
    </div>

    <footer>
        <!--Main jQuery Script-->
        <script type="text/javascript" src="script.js"></script>    
    </footer>
    
</body>
    
</html>

 

Checkout Live Demo and download full code for FREE!

 

Live Demo

Share Button

PHP, MySQL, OOP Login Form Complete Example – Live Demo

Share Button

This is a complete example of a PHP MySQL Login Form.

Let’s start.

PHP, MySQL login form consists of:

Login, Password inputs & submit button
Custom Logo on top of the form
Error checking
Sessions with redirection to different page
Form Logout

php_mysql_login_form_s_shot

 

Live Demo

 

In order to start we need to create a Table that will store all login details.

CREATE DATABASE sharemyweb;

 

After a database is created, let’s create a table with some example data:

CREATE TABLE userLogin (
id INT(10) AUTO_INCREMENT PRIMARY KEY,
login VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL) 

 

 

Each time we add some new login detail, id will be auto incremented so we don’t need to do it manually.
Next we’re going to apply a MySQL class which will make MySQL connection, run login query, escape values and authenticate login & password input, close database connection.

<?php
/* Require MySQL Credentials : */
require_once("conf.php");

class MySQL{

    public $connection;

    /* Class constructor */
    function __construct() {
        $this->open_connection();
        $this->real_escape_string_exists = function_exists("mysqli_real_escape_string");    
    }

    /* Open MySQL Connection */
    public function open_connection() {
    /* Try connection */
        try {
            $this->connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
        }

        /* Catch Exception*/
        catch(Exception $except) {
            die("Unable to connect to Database");
        }
    }
        
    /* Run sql Query */
    public function query($sql){
        $result = mysqli_query($this->connection, $sql);         
        return $result;
    }
    
    /* Find entries by sql query */
    public function find_by_query($query=""){        
        $result=mysqli_query($this->connection,$query);        
        /* Associative array */
        $row=$this->fetch_array($result);
        return $row;
    }

    /* Fetch array and return result */
    public function fetch_array($result){
        return mysqli_fetch_array($result,MYSQLI_ASSOC);
    }
    
    /* Escape unwanted characters like slashes etc. */ 
    public function escape_value($value){
        $value = trim($value);
        /* PHP v4.3.0 or higher */
        if($this->real_escape_string_exists) {
            /* If magic quotes are active */ 
            if(get_magic_quotes_gpc()){ 
                /* Strip slashes */
                $value = stripslashes($value); 
            }
            /* Escape special characters in a string */
            $value = mysqli_real_escape_string($this->connection, $value);
        }
        else{
            // Before PHP 4.3.0
            if(!$this->magic_quotes_active){
                $value = addslashes($value);
            }
        }
        return $value;
    }
    
    /* Login authentications */
    public function authenticate($login="", $password=""){
        /* Sanitize input : Escape unwanted charactets */
        $login = $this->escape_value($login);
        $password = $this->escape_value($password);
        
        /*  Run query - Remember to put LIMIT 1 at the end of query in order to return
            only 1 row 
        */
        $sql = "SELECT login,password FROM userLogin " ;
        $sql .= "WHERE login = '{$login}' ";
        $sql .= "AND password = '{$password}' ";
        $sql .= "LIMIT 1";
        
        $result_array = $this->find_by_query($sql);
        return $result_array;
        
        /* Close connection everytime we don't need to run any more queries */
        $this->close_connection();
    }
    
    /* Close MySQL Connection */
    public function close_connection()
    {
        if(isset($this->connection))
        {
            $this->connection->close();
            unset($this->connection);
        }
    }
    
}// class End
?>

 

Remember! We’ll have to open a conf.php file and change MySQL Database credentials in order to successfully connect to database. you’ll find there a defined constant that’s awaiting your new Database detail. It looks like this:

/**
* The base configurations of MySQL settings.
*
*  Database Constrants
*  If consttants are defined : CONNECT if NOT defined :  DEFINE CONSTANTS
*
*  FILL values below! Otherwise, there'll be no Database Connection.
*/


/** MySQL Server / hostname .... optionally localhost*/
defined("DB_SERVER") ? null : define("DB_SERVER", "127.0.0.1");

/** MySQL Database to be Connect to*/
defined("DB_NAME") ? null: define("DB_NAME", "sharemyweb");

/** MySQL database username */
defined("DB_USER") ? null : define ("DB_USER", "your_DB_user");

/** MySQL database password */
defined("DB_PASSWORD") ? null : define ("DB_PASSWORD", "your_DB_password");

/** Database Charset to use in creating database tables. */
defined('DB_CHARSET') ? null : define('DB_CHARSET', 'utf8');

 

Markup  of the form is easy and straightforward so I won’t explain it that much.
You’ll see it when you download full example.

Below code shows an ValidateErrors class that will take care of input errors in the form.
You can add your own errors and call them later on during input validation.
This class in more than helpful and applies easy ways of checking and displaying errors when working with bigger form when you need to validate.
You can find another example usage of this class with some extra REGEX validation here:
LINKG TO THE POST CLASS.

<?php 
/** Simple Error Class *
* - Define Error Messages, Regular Expressions 
* - Log Errors to Error Array * - Sanitize Input 
* - Print/Display Errors 
*  Please Note that this class does it's job, but you may want to do things 
* different way or change something here & there. 
* This Class gives a Patern/shows the way, of how errors could be handled in OOP way. 
* Feel free to modify,use and reffer it anyway you want. 
*/ 

class ValidateErrors{ 

/** Error Array for all Errors Occured during Validation/Check process */ 
public $errors=array(); 

/** 
* validate_errors array stores information about Errors. 
* i.e. 'ERROR NAME' = > 'ERROR MESSAGE'
*/    
    /** Errors types - You can add your ow errors if you wish */
    protected function validationErr(){
        /* Array with error types */
        $this->validate_errors = array(
            "ERR_EMPTY_LOGIN"       =>  "Login field is empty",
            "ERR_EMPTY_PASS"        =>  "Password field is empty",
            "ERR_WRONG_DETAILS"     =>  "Wrong login or password"
        );        
        /** Return Error Array */
        return $this->validate_errors;
    }
        
    /** Logs an Error to Regular Error Array */
    public function logErrors($error){
        $this->errors["$error"] = $this->validationErr()["$error"];
    }
    
    /** Check if there are any errors in Error Array */
    public function noErrors(){
        if(empty($this->errors)){
            return true;
        } else {
            return false;
        }
    }
    
    /** If login field is empty log error to the error array */
    protected function emptyLogin($login){
        if(empty($login) || is_null($login) || !$login){
            /** Log Error to the Errors Array */
            $this->logErrors("ERR_EMPTY_LOGIN");
        }
    }
    
    /** If password field is empty log error to the error array */
    protected function emptyPass($password){
        if(empty($password) || is_null($password) || !$password){
            /** Log Error to the Errors Array */
            $this->logErrors("ERR_EMPTY_PASS");
        }
    }
        
    /** Below function check & display any number of arguments passed 
    *   Each argument should represent the key(Error) of FormErrors
    *   example use: printErrors("ERR_NO_NAME","ERR_REG_NAME")
    */
    public function printErrors(){  
        /**  Returns the number of arguments passed to the function */
        $numOfArgs = func_num_args();  
        /** Returns an array with all arguments passed to the function */   
        $listOfArgs = func_get_args();
        /** Loop through array & display results */
        for ($i = 0; $i < $numOfArgs; $i++) { if(!empty($this->errors)){
                if(array_key_exists($listOfArgs[$i],$this->errors)){
                    echo $this->errors[$listOfArgs[$i]];
                }
            }
        }
    }
    
    /** Pass functions you would like to check for a $_POST['name]/$name */
    public function checkErrors($login,$pass){
        
        /** Check for Conditions/ */
        $this->emptyLogin($login);
        $this->emptyPass($pass);
        
        /** Check for Errors in Error Array */
        if(!$this->noErrors()){
            return false;
        }else{
            return true;
        }   
    }    
} // Class End

 

After we’ve specified all errors types we would like to be displayed when occur, we can call printErrors() which specifies errors to be checked for like this:

<?php
    /* Chosen error types to be printed */
    if(isset($errors))
        $errors->printErrors("ERR_EMPTY_LOGIN","ERR_EMPTY_PASS","ERR_WRONG_DETAILS");
?>

 

Example of form with wrong input:

php_mysql_login_form_s_shot_wrong_input

 

Login & Password used withing Live Demo are:

Login:           sharemyweb

Password:   password

 

As It’s a complete login form example I’m going to show you how to make save a logged user to session.
It’s a very simple way to do so. I’ve created an authorized.php page to which we’ll be redirected after successful log in.

 

php_mysql_login_form_s_shot_authorized
After we are redirected to authorized.php page we won’t be able to go back to login page for as
long as we’re logged in.

 

Checkout Live Demo and  download full code for FREE!

Live Demo

 

Share Button

jQuery Textarea Character Counter – Live Demo

Share Button

Below code allows users to keep track on total number of characters in the text area. Total number of remaining characters will be displayed to give user a hint how many characters they’ve got left to use. In addition to character counter I’ve applied a character percentage bar that visualize remaining characters… just for fun(and because it looks cool).

 

There are 3 files to the code:

index.html  – HTML

script.js       – jQuery Code

styles.css    – CSS

 

jquery_character_counter

Live Demo

 

 

jQuery Code:

 

Here’s a jQuery code that will do all the magic. The code will count characters and return the remaining characters to be entered. Counting will be triggered on keyup() event. Also program will prevent entering extra characters and delete them.  Each time the total character count changes the character percentage bar will change it’s value as well. Appropriate comments were applied throughout the code.

 

script.js

// Run funtion on page load
$(document).ready(function(){
    //Total characters allowed in textarea
    var totalChars     = 100; 
    // Text area
    var countTextBox    = $('#textArea')    
    // Characters count
    var charsCounter    = $('#characterCounter');

    // Display total characters allowed on page load - initial value of characters 
    charsCounter.text(totalChars);

    // Percentage bar
    var percentageBarCount =$("#charsCounterBar").width();

    /* Action on event - Keydown */
    countTextBox.keyup(function() { 

        // Characters in text area         
        var charsInTextArea = this.value.length;

        // If characters exceed initial value(More characters than specified)
        if(charsInTextArea > totalChars)
        {
            /* Calculate extra characters to be deleted */
            var removeCharacters = (charsInTextArea-totalChars); 

            //If characters exceed total number of characers - REMOVE extra characters
            this.value = this.value.substring(0,totalChars);

            // hide character percentage bar
            $("#charsCounterBar").hide();
        }
        else{        
            /* Count remaining characters(Initial value - )
             i.e. 200-1=199 chracters remaining, 200-21 = 179 characters remaining.
             */
            charsCounter.text( totalChars - charsInTextArea );
            // show character percentage bar
            $("#charsCounterBar").show();
        }

        // percentage of characters remaining
        var getPercChars = charsInTextArea/totalChars;            
        // apply percentage of characters remaining to percentage bar
        var getPercToRemove = percentageBarCount*getPercChars;
        // update bar width by calculating new width
        var newPercentageBarValue = percentageBarCount-getPercToRemove;

        // update new width/length of character percentage bar
        $("#charsCounterBar").css("width",newPercentageBarValue)

    });
});

 

HTML Code:

 

Below is the markup for Character Counter. HTML is simple and I’ve applied a ShareMyWeb Logo above the Character Counter so you know that you can apply your own if you wish. Feel free to change, remove it … whatever 😉

 

index.html

<!DOCTYPE html>

<html>
    <head>
        
        <title>jQuery Textarea Character Counter with Characters percentage bar</title>        
        <!--ShareMyWeb.com Icon -->
        <link rel="shortcut icon" type="image/x-icon" href="http://sharemyweb.com/wp-content/uploads/2016/01/ShareMyWeb_Favicon.png" />         
        <!--CSS Styles-->
        <link rel="stylesheet" href="styles.css">
        <!--jQuery -->        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <!--Main jQuery Script-->
        <script type="text/javascript" src="script.js"></script>
            
    </head>
    
    <body>  
        
        <div id='textAreaHolder'>
            
            <a id="shareMyWeb_link" class="logo" title="ShareMyWeb.com" href="http://sharemyweb.com/">
                <img id='shareMyWeb_logo' title="ShareMyWeb" alt="ShareMyWeb.com" src="http://sharemyweb.com/wp-content/uploads/2016/01/Fb_Sharemyweb_Logo_centered.png">
            </a>

            <textarea id="textArea" rows="5" placeholder="Visit ShareMyWeb.com"></textarea>
            
            <p>Remaining characters: 
                <strong>
                    <span name="characterCounter" id="characterCounter"></span>
                </strong>
            </p>
            
            <div id='charsCounterBar'></div>
            
        </div>

</body>
</html>
    

 

CSS Code:

 

styles.css

CSS is just an extra to the code, download the code and try it yourself.

 

You can copy paste code from the page or simply download entire code from demo page.

 

Live Demo

 

Share Button

PHP Regular Array CRUD Operations Class

Share Button

<?php

/**
*   @Autor:     Kwacho - Michal Kwasniewski
*   @Website:   www.sharemyweb.com
*
*   NOTE: Feel free to edit, change and use this class...just DON'T FORGET TO LINK WEBPAGE.
*
*   WORKING WITH REGULAR ARRAYS : Basic CRUD Functionalities
*
*        CREATE entry:   add item/items to array
*        READ   entry:   display all items in array
*        UPDATE entry:   rename/update item in array
*        DELETE entry:   delete item/items from array
*
*/

// Class Start
class CRUD_Arrays{

   // Items Array with dummy data
   public static $itemsArray=array("one","two","three");

   // HELPER METHODS that will be necessary to work with main CRUD methods

   /* Checks if array is empty */
   private function isEmptyArray($array){
      if(empty($array))
      return false;
   }

   /* Check If item is in array */
   private function checkIfItemExist($item){
      if(in_array($item,self::$itemsArray)){
         return true;
      } else {return false;}
   }

   /*  Find an item and returns its corresponding index.
   *   If item is not in array, display apporpriate message
   */
   private function findItem($item){
      if($this->checkIfItemExist($item)){
         $this->getItem = array_search($item,self::$itemsArray);
         /* Return it as string, otherwise if array index resoves to 0,
         *  renameItem() method does not want to rename first/[0] value 
         */
         return "{$this->getItem}";
      }else{
         echo "There's no " . $item . " in array";
      }
   }

   //MAIN CRUD Functionalities

   /*  Add item/items to array. You can pass as many arguments as you wish.
   *    If any of the items already exists it will NOT be added again or ducplicated
   */
   public function addItems(){
      /**  Returns the number of arguments passed to the function */
      $numOfArgs = func_num_args();
      /** Returns an array with all arguments passed to the function */
      $listOfArgs = func_get_args();

      /** Add Items to array */
      for ($i = 0; $i < $numOfArgs; $i++) {
         array_push(self::$itemsArray,$listOfArgs[$i]);
      }
   }

   /* Loops through an array and dispalys all items */
   public function displayItems($items){
      foreach($items as $item){
         echo "<li>{$item}</li>";
      }
   }

   /* Renames/Changes/Updates an item to another item/item name */
   public function renameItem($item,$newItem){
      if($this->findItem($item) != null){
         self::$itemsArray["{$this->findItem($item)}"] = $newItem;
      }
   }

   /* Clear Array: a) $itemsArray = NULL, b) $itemsArray = array()*/
   public function clearArray(){
      //self::$itemsArray = NULL;
      self::$itemsArray = array();
   }

   /*  Deletes specific item/items from array.
   *   You can pass as many arguments as you wish.
   */
   public function deleteItems(){
      /**  Returns the number of arguments passed to the function */
      $numOfArgs = func_num_args();
      /** Returns an array with all arguments passed to the function */
      $listOfArgs = func_get_args();
      /** Delete items from array */
      for ($i = 0; $i < $numOfArgs; $i++) {
         if($this->checkIfItemExist($listOfArgs[$i])){
            $this->getItem = array_search($listOfArgs[$i],self::$itemsArray);
            unset(self::$itemsArray[$this->getItem]);
         }
      }
   }
}   // Class end

?>

 

EXAMPLE USE:

 

Firstly, let’s instantiate array so we can access all methods we want.

/* Instance of a CRUD_Arrays class */
$arrayClass = new CRUD_Arrays();

 

Secondly, we’re going to display all items. At the beginning we’ve put some dummy
data to array to have something to work with.
displayItems() method will loop through an array of items and display all of them.
It’s a raw output, but if you wish you can add some markup to it.

echo "<ul>" . $arrayClass->displayItems(CRUD_Arrays::$itemsArray) . "</ul>";

Screen Shot 2016-01-12 at 12.58.43

 

Now we’re going to add few items to array. Below method addItems() adds one item to array.

$arrayClass->addItems("four");

It’s possible to add more than one item to array at the same time using the same method as above.

$arrayClass->addItems("five","six","seven");

Screen Shot 2016-01-12 at 13.02.22

 

Now we can check how deleteItems() method works. Same as addItem() method, deleteItem() allows
to delete one or more arguments from array at the same time.

$arrayClass->deleteItems("one");

OR

$arrayClass->deleteItems("two","three");

Screen Shot 2016-01-12 at 13.02.42

 

Wen can also rename items. renameItem() method takes two arguments : item to be changes, new item. Simple right?

echo $arrayClass->renameItem("five","FIVE");
echo $arrayClass->renameItem("seven","SEVEN");

Screen Shot 2016-01-12 at 13.03.02

 

 

Just Copy Paste CRUD_Arrays class and have a go.

Share Button

PHP MySQL Connection With PDO

Share Button

<?php

/**
*
*  MySQL Connection with PDO
*  Fill Values below with your own MySQL Database Credentials
*
*   if constants are defined:       CONNECT
*   if constants are NOT defined:   DEFINE CONSTANTS
*   NOTE: It’s a good practice to keep Constants in separate file with appropriate permissions
*      
**/

/** server - 127.0.0.1 or localhost */
defined("DB_SERVERR") ? null : define("DB_SERVER", "127.0.0.1");
/** MySQL database */
defined("DB_NAME") ? null: define("DB_NAME", "your_db_name");
/** MySQL username */
defined("DB_USER") ? null : define ("DB_USER", "your_username");
/** MySQL password */
defined("DB_PASSWORD") ? null : define ("DB_PASSWORD", "your_password");
/* MySQL host & database name parameters */
defined("MYSQL_HOST_AND_DBNAME") ? null : define ("MYSQL_HOST_AND_DBNAME", "mysql:host=".DB_SERVER.";"."dbname=".DB_NAME);
class MySQL_PDO_CONN{

private $connection;

// Constructor
function __construct()
{
$this->open_connection();
}

/* Open MySQL Connection */
public function open_connection()
{

/* Try connection */
try {
$connection = new PDO(MYSQL_HOST_AND_DBNAME, DB_USER, DB_PASSWORD);

/* echo connection message */
echo 'Connected to Database<br/>';

/* Close connection */
$db = null;
}

/* Catch Exception*/
catch(PDOException $e)
{
echo $e->getMessage();
}

}
}// class End
/** Instance of a MySQL_PDO_CONN class 
*   Notice that there's no need to call open_connection() method as it
*   was already called in constructor
*/
$connect = new MySQL_PDO_CONN();

?>

Share Button

Set MySQL root password on OS X

Share Button

Login To MySQL with:

$ mysql -u root

 

Set new password for MySQL User: (‘Kwacho’ is our new password)

mysql> Use mysql;
mysql> UPDATE user SET password=PASSWORD("Kwacho") WHERE user='root';
mysql> FLUSH PRIVILEGES;
mysql> quit

 

Login to MySQL with new Password: (Password is Capitalized!)

$ mysql -u root -p

 

If You’ll get an error of a type:

bash: mysql: command not found

It means that You’ll need to update you $PATH environment variable

 

Try with Following Command: (full path to mysql)

$ /usr/local/mysql/bin/mysql -u root -p Kwacho

 

Share Button