Blogaddition - A Technical Blog For Programmers | PHP | Jquery | Ajax | HTML5 | CSS3 | Mysql | Programming Tutorials And DemoBlogaddition - A Technical Blog For Programmers | PHP | Jquery | Ajax | HTML5 | CSS3 | Mysql | Programming Tutorials And Demo http://blogaddition.com Technology never ends Wed, 04 Dec 2013 03:49:52 +0000 en-US hourly 1 Know Data Integrity And Consistency Through Trigger http://blogaddition.com/2013/12/know-data-integrity-and-consistency-through-trigger/ http://blogaddition.com/2013/12/know-data-integrity-and-consistency-through-trigger/#comments Wed, 04 Dec 2013 03:47:36 +0000 Gokaran Tiwari http://blogaddition.com/?p=564 myspacedataavailability_270x270

Hi,  This is my first post on blogaddition.com. In this tutorial, I'll talk about "Data Integrity And Consistency Through Trigger" in MYSQL. As we know that, It is very important for data in a database to be accurate and correct.There are various methods to ensure this , but triggers have their own significance in maintaining the integrity and consistency of data.

Data Integrity And Consistency Through Trigger

A trigger can be used to ensure and enforce business rules and data integrity and enable the performance of complex actions and cascade these actions to other dependent tables.

Business rules refer to the policies of an organization , which ensure that it’s business runs smoothly .

Data Integrity  refers to the accuracy and reliability of data.

For Example , an item can be sold only if sufficient stack is available . If a trigger is used , it would check against incorrect transactions and ensure that only valid data is inserted in table.

Basically Trigger  is a pre-compiled database object which consists a set of T-Sql statement that are activated in response to certain action.It is fired whenever data in the underlying table is affected by any of the Data Manipulation Language(DML) statements-INSERT , UPDATE ,or DELETE.

Characteristic of Trigger :

1) Trigger is fired automatically by database server whenever any data modification statement is issued.

2) Trigger can not be explicitly invoked or executed , as in the case of stored procedures.

3) Trigger Prevents incorrect , unauthorized , and inconsistent changes in database.

4) Trigger can not return data to user.

Have a look at the following example.

[code lang="sql"] CREATE TABLE `account` ( `account_id` INT(11) NOT NULL AUTO_INCREMENT, `account_name` VARCHAR(200) DEFAULT NULL, `balance` DOUBLE DEFAULT ’0′, PRIMARY KEY (`account_id`) ) CREATE TABLE `withdrawl_details` ( `withdrawl_id` INT(11) NOT NULL AUTO_INCREMENT, `account_id` INT(11) NOT NULL, `withdrawl_amount` DOUBLE DEFAULT ’0′, PRIMARY KEY (`withdrawl_id`) ) DELIMITER $$ DROP TRIGGER account_trigger`$$ CREATE TRIGGER `account_trigger` BEFORE INSERT ON `withdrawl_details` FOR EACH ROW BEGIN DECLARE msg VARCHAR(255); DECLARE available_balance DOUBLE DEFAULT 0; SET available_balance=(SELECT balance FROM account WHERE account_id=NEW.account_id); IF (available_balance-NEW.withdrawl_amount<0) THEN  SIGNAL SQLSTATE `45000` SET MESSAGE_TEXT = `’Withdrawl amount is more than available balance in account.’`;  END IF ; END; $$ DELIMITER ; [/code]

Result :- whenever an attempt made to withdrawal amount and balance is insufficient then account_trigger will prevent to maintain the business rules.

]]>
http://blogaddition.com/2013/12/know-data-integrity-and-consistency-through-trigger/feed/ 0
Facebook Style Link Preview Using Jquery And Simple HTML Dom http://blogaddition.com/2013/10/facebook-style-link-preview-using-jquery-and-simple-html-dom/ http://blogaddition.com/2013/10/facebook-style-link-preview-using-jquery-and-simple-html-dom/#comments Mon, 07 Oct 2013 17:09:00 +0000 Manish Jangir http://blogaddition.com/?p=522 Facebook Style Link Preview Using Jquery And Simple HTML Dom

Facebook Style Link Preview Using Jquery And Simple HTML Dom

Hi friends, Today I've brought a very interesting tutorial (specially for Jquery and Ajax beginners). In this post, I'm going to teach you, that how to create a facebook style link preview widget in your website. I don't know which technologies does facebook use to grab the link or url data but in this tutorial, I've used PHP's simple html dom parser and jquery to make this awesome project.  If you don't have any idea about simple html dom then let me explain a brief about this.

Facebook Style Link Preview Using Jquery And Simple HTML Dom

[button link="http://demo.blogaddition.com/facebook_link_preview" target="_blank" color="green" shape="rounded" size="large" align="left"]Live Demo[/button][button link="http://blogaddition.com/wp-content/uploads/2013/10/facebook_link_preview.zip" target="_blank" color="blue" shape="rounded" size="large" align="left"]Download[/button]

Simple HTML Dom:

First of all, this is a  PHP's dom parser class that I love very much always as it has helped me a lot in my past to make the crawling applications with php. Simple Html Dom is another "kind of Jquery" that is written in PHP 5 to manipulate both valid and invalid HTML on server side.  It can find tags on an HTML page with selectors and extract contents from HTML in a single line just like jQuery. That's why, It can be used better in developing the crawling applications and grabbing data from other websites.

The application contains following files:

1. simple_html_dom.php :

This is the dom parser class included for grabbing the meta data from provided url in the textarea.

2. get.php :

This file gets the url requested through ajax and validate it with curl either it has any html content or redirected to another link.  Sometimes the url is redirected to another  address for eg. If you type www.yahoo.com in the browser, then it is redirected to "http://in.yahoo.com/?p=us" and curl finds no html on yahoo.com url. So  I've used curl's "CURLINFO_EFFECTIVE_URL" parameter  to get the last redirected url and pass it again in the curl to get the html content.

[code lang="php"] /** * Grabs Meta Data For The Link * @author Manish Jangir * @copyright 2013 Manish Jangir Production */ ini_set('max_execution_time', 80); function get_web_page( $url, $type="url" ) { $options = array( CURLOPT_RETURNTRANSFER => true,     // return web page CURLOPT_HEADER         => false,    // don't return headers CURLOPT_FOLLOWLOCATION => true,     // follow redirects CURLOPT_ENCODING       => "",       // handle all encodings CURLOPT_USERAGENT      => "spider", // who am i CURLOPT_AUTOREFERER    => true,     // set referer on redirect CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect CURLOPT_TIMEOUT        => 120,      // timeout on response CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects ); $ch = curl_init( $url ); curl_setopt_array( $ch, $options ); $content = curl_exec( $ch ); $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close( $ch ); if($type == "url") { return $finalUrl; } else if($type="content") { return $content; } } //Check if the given url is a valid link or not if (preg_match("/\b(?:(?:https?|ftp)://|www\.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i", $_GET['url'])) { require 'simple_html_dom.php'; $url = get_web_page($_GET['url']); //Get last redirected url $html = str_get_html(get_web_page($url,'content')); //Get HTML Of That Link $data = array(); //Prepare data array to show $data['title'] = $html->find('title',0)->innertext; //Title Of Page $data['url'] = $url; //Url Of Page Set description if desc meta tag found else grab a little plain text of the page if($html->find('meta[name="description"]',0)) { $data['description'] = $html->find('meta[name="description"]',0)->content; } else { $data['description'] = $html->find('body',0)->plaintext; } //Get all images found on this page $jpgs = $html->find('img[src$=jpg],img[src$=png]'); foreach ($jpgs as $jpg) { $data['images'][] = $jpg->getAttribute('src'); //Store them in an image key of the array } //Set Total Images for pagination in the widget $data['total_images'] = !empty($data['images']) ? count($data['images']) : 0; //Finally encode the data in JSON format and print it echo json_encode($data); } else { echo false; //Return false if provided url from textarea is not valid } ?> [/code]

After getting the html content, We iterate the html tags through dom parser and get the meta title, meta description and all images found on the page. Encoded the whole grabbed data in JSON format and used in the widget with ajax response.

3. Script.js :

This is the javascript written to handle whole client side functionality such as sending request and getting ajax response, showing it to appropriate div and image pagination. [code lang="javascript"] /** * Javascript Document For The Application * @author Manish Jangir * @copyright 2013 Manish Jangir Production */ $(document).on('keyup','#status',function(e){ if(e.which == 32) { getUrlData(); } e.stopImmediatePropagation(); }) function getUrlData() { var url = $.trim($('#status').val()); if(url != '') { $('#fb_loader').show(); resetEverything(); $.ajax({ url: "get.php", data:"url="+url, success:function(data) { if(!data) { $('#fb_loader').hide(); alert("Invalid Url"); } else { var data = $.parseJSON(data); $('span#preview_title_span').text(data.title); $('#preview_url').text(data.url); $('span#preview_desc_span').text(data.description); var imgcnt = 1; if(data.images){ $.each(data.images, function(key,value) { $('</pre> <img alt="" /> <pre>').attr({ src:value, id:'linkimage_'+imgcnt, style:'width: 130px; height: auto; display: none;' }).appendTo($('').attr({ href:data.url, target:'_blank' }).appendTo($('#preview_images_div'))); imgcnt++; }); } $('#linkimage_1').css('display','block'); $('#currimg').val(1); $('#totalimg').val(data.total_images); if(data.total_images > 0) { $('.image_count').text('1 of '+data.total_images); } else { $('.image_count').text('No images found'); } $('#preview_div').fadeIn('slow'); $('#fb_loader').hide(); } } }); } } function resetEverything() { $('#preview_images_div').html(''); $('#next_image').removeClass().addClass('next_button'); $('#prev_image').removeClass('prev_button').addClass('prev_button_disabled'); $('#preview_div').hide('fast'); } $(document).on('click','#closebtn',function(){ resetEverything(); }) $(document).on('click','#next_image,#prev_image',function() { if($(this).hasClass('next_button')) { var current = parseInt($('#currimg').val())+1; curimg = current > $('#totalimg').val() ? $('#totalimg').val() : current; } else if($(this).hasClass('prev_button')) { var current = parseInt($('#currimg').val())-1; curimg = current < 1 ? 1 : current; } $('#currimg').val(curimg); $('#preview_images_div img').hide(); $('#preview_images_div #linkimage_'+curimg).show(); $('.image_count').text(curimg+' of '+$('#totalimg').val()); $('#next_image').removeClass().addClass('next_button'); $('#prev_image').removeClass().addClass('prev_button'); if(curimg == $('#totalimg').val()) { $('#next_image').removeClass().addClass('next_button_disabled'); } if(curimg == 1) { $('#prev_image').removeClass().addClass('prev_button_disabled'); } }); $(document).on('click','.no_thumb',function(e) { $('#preview_images_div').show(); if($('#noThumb').is(':checked')) { $('#preview_images_div').hide(); } }); [/code]

4. index.php :

This is nothing or more than everything. The main index file to bind whole functionality in a single bundle. [code lang="html"] Facebook Style Link Preview Demo <script type="text/javascript" src="jquery-1.10.1.min.js"></script><script type="text/javascript" src="script.js"></script></pre> <div id="fbpreview"> <div id="fb_loader" style="display: none;"><img src="loading.gif" alt="" /></div> <div id="fblink_outer"> <div id="textarea"><textarea id="status"></textarea> <input id="totalimg" type="hidden" value="" /> <input id="currimg" type="hidden" value="" /></div> <div id="preview_div"> <div id="preview_images_div"></div> <div id="preview_content"> <div id="preview_title"><span id="preview_title_span"> </span></div> <div id="preview_url"></div> <div id="preview_desc"><span id="preview_desc_span"> </span></div> <div id="preview_buttons"> <div id="prev_image"></div> <div id="next_image"></div> <div>8 of 32</div> <div>Choose a thumbnail</div> </div> <input id="noThumb" style="display: block;" type="checkbox" /> <label id="no_thumb_text" for="noThumb">No thumbnail</label></div> <div id="closebtn" title="Remove"></div> </div> <div id="button_div"><button name="" value="" type="button">Post</button></div> </div> </div> <pre> [/code]

5. Style.css :

Don't ask me about this bloody file, that wasted too much time in writing the basic markup for the application. I spent a lot of time time to copy the styles from facebook to make it exactly like that. And I hope, I've done it perfectly. What you think?? [code lang="css"] /* CSS Document */ body { margin:0; padding:0; font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#666666; } #fbpreview { width:513px; margin: 20px auto auto; } #fblink_outer { border: 1px solid #B4BBCD; position: relative; margin:10px auto; float:left; width:100%; clear:right; } #fblink_outer #textarea { float: left; height: 54px; padding: 5px; width: 99%; } #textarea textarea{ border:none; resize: none; outline: 0 none; width:100%; line-height: 1.28; font-family:'lucida grande',tahoma,verdana,arial,sans-serif; color:#333333; font-size: 13px; height: 16px; padding: 0; resize: none; overflow: hidden; height:99%; vertical-align: bottom; } #fblink_outer #button_div { background-color: #F2F2F2; border-top: 1px solid #E6E6E6; float: left; padding: 2px; width: 99%; } button.css3button { background-color: #5B74A8; background-image: url("backgrounds.png"); background-position: 0 -49px; background-repeat: no-repeat; border: 1px solid #1A356E; color: #FFFFFF; cursor: pointer; display: inline-block; float: right; font-family: "lucida grande",tahoma,verdana,arial,sans-serif; font-size: 11px; font-weight: bold; line-height: 13px; padding: 4px 16px; text-align: center; text-decoration: none; vertical-align: top; white-space: nowrap; } #fb_loader { float: right; height: 11px; width: 16px; } #preview_div { border-top: 1px dashed #CCCCCC; float: left; font-family: "lucida grande",tahoma,verdana,arial,sans-serif; font-size: 12px; padding: 8px 5px; color:#000000; width: 98%; display:none; } #preview_images_div { float: left; margin-right: 12px; width: 130px; } #closebtn { background-image: url("close.png"); background-position: left 0; background-repeat: no-repeat; cursor: pointer; float: right; height: 15px; width: 15px; } #closebtn:hover { background-image: url("close.png"); background-position: left -32px; background-repeat: no-repeat; } #preview_content { float: left; font-size: 11px; width: 340px; } #preview_title { font-size: 12px; font-weight: bold; margin: 0 auto 2px; } #preview_url { color: #666666; font-size: 11px; margin: 0 auto 9px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 340px; } #preview_desc { margin: 0 auto 8px; width:340px; } #preview_desc_span,#preview_title_span { cursor: pointer; } #preview_buttons { margin-bottom: 39px; margin-top: 12px; width: 290px; } .prev_button:active { background-image: url("selectionButtons.gif"); background-position: -100px -83px; background-repeat: no-repeat; } .prev_button { background-image: url("selectionButtons.gif"); background-position: 0 -83px; background-repeat: no-repeat; cursor: pointer; float: left; height: 22px; width: 25px; } .prev_button_disabled { background-image: url("selectionButtons.gif"); background-position: -50px -83px; background-repeat: no-repeat; float: left; height: 22px; width: 25px; } .next_button:active { background-image: url("selectionButtons.gif"); background-position: -125px -83px; background-repeat: no-repeat; } .next_button { background-image: url("selectionButtons.gif"); background-position: -25px -83px; background-repeat: no-repeat; cursor: pointer; float: left; height: 22px; margin-right: 10px; width: 25px; } .next_button_disabled { background-image: url("selectionButtons.gif"); background-position: -75px -83px; background-repeat: no-repeat; float: left; height: 22px; margin-right: 10px; width: 25px; cursor:default; } .image_count { float: left; font-size: 10px; margin-right: 10px; margin-top: 5px; } .choose_thumbnail { color: #999999; float: left; font-size: 10px; margin-top: 5px; } .no_thumb_checkbox { float: left; margin-left: 0; margin-right: 4px; vertical-align: -2px; } #no_thumb_text { cursor:pointer; color: #333333; font-size: 11px; float: left; margin-top: 3px; width: 270px; } [/code]]]>
http://blogaddition.com/2013/10/facebook-style-link-preview-using-jquery-and-simple-html-dom/feed/ 0
Live Table Edit And Delete With Pagination Using Jquery Ajax http://blogaddition.com/2013/09/live-table-edi-and-delete-with-pagination-using-jquery-ajax/ http://blogaddition.com/2013/09/live-table-edi-and-delete-with-pagination-using-jquery-ajax/#comments Mon, 30 Sep 2013 16:57:33 +0000 Manish Jangir http://blogaddition.com/?p=475 Live Table Edit And Delete With Pagination Using Jquery Ajax

Live Table Edit And Delete With Pagination Using Jquery Ajax

Although there are many jquery plugins available on the Internet to live edit the data tables but in this article we are writing our own simple php and javascript files to achieve the same target using ajax. I'm a big fan of Shrinivas Tamada (Owner of  9lessons.info) and highly inspired by him. I always love his posts and tutorials. In this article I'm just extending one of this most popular post (Live table data edit and delete) by implementing the multiselect delete and ajax pagination. The post is very useful for the beginners who want to learn ajax and jquery with php. I've used PHP's OOPS concept and "On" event handler of jquery to reduce the direct function calling in the project. So without wasting your too much time, I move to further and start to write the application.

Dynamically Add Remove Text Box Using Jquery

Live Table Edit And Delete With Pagination Using Jquery Ajax

You will get the following files in the downloaded zip archive: 1. Index.php (Base php file to boot up the application) 2. Database.php (Handles database connection and other mysql methods) 3. Style.css (Mark up for the application to give a beautiful look) 4. Script.js (Create ajax functionality in the project using dom) 5. livetable.sql (Database sql dump to create the users table)

Now First of all we design our database and create the users table [code lang="sql"] CREATE DATABASE `livetable`; CREATE TABLE `livetable`.`users`( `id` INT(5) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50), `email` VARCHAR(100), `country` VARCHAR(50), `mobile` VARCHAR(50), PRIMARY KEY (`id`) ); [/code] Let's move next to create the basic markup and style for our application as we always do. I tried to reduce the css code too much but a branded shirt is always looks bad without its buttons. Hope you understood.

Style.css

[code lang="css"] /* CSS Document */ body { margin:0; padding:0; color:#333333; } #outer_container { width:80%; margin:0 auto; padding: 50px 10px 10px 10px; border:1px solid #ccc; font-family:Arial, Helvetica, sans-serif; font-size:12px; position:relative; } input { background:#DDF99A; border: 1px solid #B4D349; border-radius: 2px 2px 2px 2px; padding: 5px; width: 90%; } #loader{ position: absolute; text-align: center; z-index: 9999; margin:auto; display:none; top: 50%; left: 50%; } .delall { background: #1F9DBF; border: medium none; color: #FFFFFF; cursor: pointer; height: 35px; margin: 0 0 15px 45px; padding: 0 5px 2px; } #data_tbl { font-family:Arial, Helvetica, sans-serif; border-left:1px solid #ccc; border-top:1px solid #ccc; } #data_tbl tbody tr:hover{ background-color:#FFFFD2; } #data_tbl td,#data_tbl th{ padding:7px; border-right:1px solid #ccc; border-bottom:1px solid #ccc; } #data_tbl thead { background: #00b7ea; background: -moz-linear-gradient(top,  #00b7ea 22%, #009ec3 73%); background: -webkit-gradient(linear, left top, left bottom, color-stop(22%,#00b7ea), color-stop(73%,#009ec3)); background: -webkit-linear-gradient(top,  #00b7ea 22%,#009ec3 73%); background: -o-linear-gradient(top,  #00b7ea 22%,#009ec3 73%); background: -ms-linear-gradient(top,  #00b7ea 22%,#009ec3 73%); background: linear-gradient(to bottom,  #00b7ea 22%,#009ec3 73%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00b7ea', endColorstr='#009ec3',GradientType=0 ); color: #FFFFFF; font-weight: bold; height: 35px; } .updrow,.delrow{ cursor:pointer; } #paginator { margin: 15px auto; width: 91%; } .pagin { padding: 10px 0; font:bold 11px/30px arial, serif; } .pagin * { padding: 2px 6px; color:#3A3B2D; margin: 2px; border-radius:3px; } .pagin a { border:solid 1px #036E92; text-decoration:none; background:#F8FCFF; padding:6px 7px 5px; } .pagin span, a:hover, .pagin a:active, .pagin span.current { background: -moz-linear-gradient(center top , #088899 1px, #036E92 1px, #049DB8) repeat scroll 0 0 rgba(0, 0, 0, 0); color: #FFFFFF; } .pagin span,.current{ padding:8px 7px 7px; } [/code]

Script.js For Jquery Operations

[code lang="javascript"] //JavaScript Document $(document).ready(function(){ load('action=ajax&page=1'); //Load by default first page on load }); $(document).on('click','.pagin a', function(){ load('action=ajax&page='+$(this).attr('id')); //Load data when click on pagination }) function load(str) { $("#loader").fadeIn('slow'); $('#data').load('index.php?'+str,function() { $("#loader").fadeOut('slow'); }); } //Select All with checkbox functionality $(document).on('click','input:checkbox',function(e) { if($(this).hasClass('selall')) { $('.selrow').prop({checked:$(this).is(':checked')}); } else { if($('.selrow:checked').length == $('.selrow').length) { $('.selall').prop({checked:true}) } else { $('.selall').prop({checked:false}) } } }); //Functionality for single or multiple delete $(document).on('click','.delall,.delrow',function(e){ var id; if($(this).hasClass('delall')) { e.preventDefault(); id = $('.selrow:checked').map(function(){ return $(this).val(); }).get(); } else { id = $(this).parents('tr').find('input:hidden').val(); } if($('.selrow:checked').length == 0 && $(this).hasClass('delall')) { alert('Please select atleast one row'); } else if(confirm('Do you really want to delete')) { load('action=delete&page=1&id='+id); } e.stopImmediatePropagation(); }); //Save updated data in database function savedata() { if($('.modified').length > 0) { $('.modified').each(function(e){ $tr = $(this); $tr.find('input:text').hide(); $.post('index.php?'+$tr.find(':input').serialize()+'&action=update',function() {}); $tr.find('span').show(function(){ $(this).text($(this).next('input').val()).next('input').remove(); }); $tr.css('background-color','#F5E6DA').removeClass('modified').find('img').show(); }); } } //Save data when click anywhere on page body $(document).on('click','html',function(e){ if(! $(e.target).is(':input')) { savedata(); } e.stopImmediatePropagation(); }); //Show input boxes in row when click on update icon $(document).on('click','.updrow',function(e){ $(this).hide(); $tr = $(this).parents('tr'); $tr.addClass('modified'); $tr.css('background-color','#686C70'); $tr.find('span').each(function(){ $(this).hide(function(){ $(this).after('<input type="text" name="'+$(this).attr('class')+'" value="'+$(this).text()+'" maxlength="35" />'); }); }); e.stopImmediatePropagation(); }); [/code]

Database.php For Database and Pagination

[code lang="php"] <?php /** * Database Class * @author Manish Jangir */ class Database { const DB_HOST = 'localhost'; const DB_USER = 'root'; const DB_PASSWORD = ''; const DB_NAME = 'livetable'; private $_dbconnect = NULL; private $_table = 'users'; private $_adj = 4; private $_tpages = 0; private $_limit = 5; private $_offset= 0; private $_page = 1; private $_prev_lbl = '&lsaquo; Prev'; private $_next_lbl = 'Next &rsaquo;'; public function __construct() { $this->_dbconnect = mysql_connect(self::DB_HOST,self::DB_USER,self::DB_PASSWORD); if ($this->_dbconnect) { $db =  mysql_select_db(self::DB_NAME,$this->_dbconnect); } else { die(mysql_error()); } $this->_page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1; $this->_offset = ($this->_page - 1) * $this->_limit; } private function total() { $result = mysql_query("select count(id) AS total FROM $this->_table"); $row = mysql_fetch_array($result); return $row['total']; } public function get_users() { $query = mysql_query("SELECT * FROM $this->_table ORDER BY id DESC LIMIT $this->_offset,$this->_limit"); $result = array(); $i = 0; while($res = mysql_fetch_assoc($query)){ $result[$i] = $res; $i++; } return $result; } public function delete($id){ $ids = is_array($id) ? implode(',', $id) : $id; $query = mysql_query("DELETE FROM $this->_table WHERE id IN ($ids)"); return $this->result($query); } public function insert($data) { $keys = implode(',', array_keys($data)); $values = "'" . implode("','", array_values($data)) . "'"; $query = mysql_query("INSERT INTO $this->_table ($keys) VALUES ($values)"); return $this->result($query); } public function update($data) { $id = $data['id']; unset($data['id']); $query = "UPDATE $this->_table SET "; foreach ($data as $key => $value) { $params[] = $key." = '".$value."'"; } $query .= implode(',', $params)." WHERE id = $id"; return $this->result(mysql_query($query)); } private function result($q) { return $q ? true : false; } public function paginate() { $this->_tpages = ceil($this->total()/$this->_limit); $out = '<div>'; if($this->_page == 1) { $out .= "<span>$this->_prev_lbl</span>"; } else { $out .= "<a href='javascript:void(0);' id='".($this->_page-1).")'>$this->_prev_lbl</a>"; } $out.= ($this->_page>($this->_adj+1)) ? "<a href='javascript:void(0);' id='1'>1</a>" : ''; $out.= ($this->_page>($this->_adj+2)) ? $out.= "...\n" : ''; $pmin = ($this->_page>$this->_adj) ? ($this->_page-$this->_adj) : 1; $pmax = ($this->_page<($this->_tpages-$this->_adj)) ? ($this->_page+$this->_adj) : $this->_tpages; for($i=$pmin; $i<=$pmax; $i++) { if($i==$this->_page) { $out.= "<span class='current'>$i</span>"; }else { $out.= "<a href='javascript:void(0);' id='$i'>$i</a>"; } } $out. ($this->_page<($this->_tpages-$this->_adj-1)) ? $out.= "...\n" : ''; $out.= ($this->_page<($this->_tpages-$this->_adj))? $out.= "<a href='javascript:void(0);' id='$this->_tpages'>$this->_tpages</a>" : ''; if($this->_page<$this->_tpages) { $out.= "<a href='javascript:void(0);' id='".($this->_page+1)."'>$this->_next_lbl</a>"; }else { $out.= "<span>$this->_next_lbl</span>"; } $out.= "</div>"; return $out; } } ?> [/code]

Index.php Base File

[code lang="php"] <?php $action = (isset($_REQUEST['action']) && !empty($_REQUEST['action']))?$_REQUEST['action']: NULL; if(empty($action)) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Jquery Ajax Live Table Edit</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="jquery-1.10.1.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <div id="outer_container"> <div id="loader" ><img src="loader.gif"></div> <div id="data" style="position:relative;"> <?php } ?> <?php if(empty($action)) {?> </div> </div> </body> </html> <?php } if($action == 'ajax' || $action == 'update' || $action == 'delete') { require_once 'database.php'; $db = new Database; function getTable() { GLOBAL $db; $data = '<button>Delete Selected</button> <form><table width="90%" cellspacing="0" cellpadding="2" align="center" border="0" id="data_tbl"> <thead> <tr> <th width="5%"><input type="checkbox"/></th> <th width="25%">Name</th> <th width="25%">Email</th> <th width="17%">Country</th> <th width="18%">Mobile</th> <th width="10%">Action</th> </tr> </thead> <tbody>'; $i = 1; $cls = false; foreach ($db->get_users() as $value) { $bg = ($cls = !$cls) ? '#ECEEF4' : '#FFFFFF'; $data .='<tr style="background:'.$bg.'"> <td><input type="checkbox" value="'.$value['id'].'"/> <input type="hidden" value="'.$value['id'].'" name="id" /> </td> <td><span>'.$value['name'].' </span></td> <td><span>'.$value['email'].'</span></td> <td><span>'.$value['country'].'</span></td> <td><span>'.$value['mobile'].'</span></td> <td align="center"> <img src="edit.png" title="Update"/>&nbsp; <img src="delete.png" title="Delete"/> </td> </tr>'; $i++; } $data .='</tbody> </table></form> <div id="paginator">'.$db->paginate().'</div>'; return $data; } if($action == 'ajax') { echo getTable(); } else if($action == 'delete') { $db->delete($_REQUEST['id']); echo getTable(); } else if($action == 'update') { unset($_REQUEST['action']); $db->update($_REQUEST); } } ?> [/code] Simple download the zip file and extract in your root folder to run the application straight forward. Live Table Edit And Delete With Pagination Using Jquery Ajax]]>
http://blogaddition.com/2013/09/live-table-edi-and-delete-with-pagination-using-jquery-ajax/feed/ 5
What Are CSS Preprocessors And How To Use Them? http://blogaddition.com/2013/09/what-are-css-preprocessors-and-how-to-use-them/ http://blogaddition.com/2013/09/what-are-css-preprocessors-and-how-to-use-them/#comments Wed, 25 Sep 2013 16:33:21 +0000 Manish Jangir http://blogaddition.com/?p=442 What Are CSS Preprocessors And How To Use Them?

What are CSS Preprocessors And How to use them

One morning in the office, I had a look at the computer screen of one of my colleagues Jitendra Thakur while shaking hands with him. He was reading about a very funny word “SASS”. Why funny?? Because SASS is generally tends to “Mother in Law” in India :P but here it has a technical meaning and that’s “CSS Preprocessor”. Jitendra asked me to share something about CSS Preprocessors and literally,  I didn't know a anything about them. But finally I decided to write some informative about CSS Preprocessors to make both Jitendra and my readers understand. Before we move further, we have a quick look at CSS first.

What Are CSS Preprocessors And How To Use Them?

Weakness of CSS:

Although CSS is the beauty of any web application and the web designers are beauty parlor men that work very hard and spend much time in writing a lot of CSS files each day. But have they thought about the weakness of this web beauty ever? Listed in the following.

1. Designers have to write thousands of lines of code because CSS doesn’t allow them to reuse the rules of an element for multiple selectors.

2. CSS has its own feature set that doesn’t offer to use variables, conditional statements (If Else), loops as other programming languages do.

3. Hard to manage or import multiple files in one single CSS.

To overcome these limitations, a new concept of CSS Preprocessors was introduced in recent years and the web designers love them and very happy to adopt this exciting concept in their project.

What are CSS Preprocessors?

Stop once! If you are a beginner and still learning CSS, this tutorial is not for you. Gain an expertise in CSS first by playing with it for a long time and then come back here. This post is only for the people who are able to write a clean CSS code fast and efficiently.

CSS Preprocessor is just like a tool or software that offers a very advance CSS coding.  This advanced CSS is written in a preprocessed language (eg. SASS, LESS or STYLUS) and then complied by the tool (depends on which CSS Preprocessor are you using) and outputs a normal old style CSS file. These tools allow the designers to adopt more programming concepts in their design and let them feel become a developer too. There are three most popular CSS Preprocessors (SASS, LESS and STYLUS) have been borned that have made a very good place in the world of web designing.

Which Preprocessors Should You Use?

It depends on a lot of factors that which CSS preprocessor you should adopt in your theme because all of them have their own syntax, advantages, disadvantages and flexibility of writing the code. As I read the reviews and according to my research,” LESS “has been loved a lot by people because it is written in JavaScript and you all are familiar with JavaScript (You use it daily with jquery) in some manners.

How to start with a preprocessor?

Getting started with a CSS preprocessor is very straight forward. What you need to setup and start with a preprocessor is elaborated below:

1. Choose a suitable preprocessor (SASS, LESS and STYLUS are most popular and many others are also available).

2. Install the respected compiler either in your computer or production server (I’ll explain how many ways the preprocessors can be used).

3. Start writing the advanced CSS files in the preprocessed language (.sass, .less or .styl) using a suitable editor like eclipse etc.

4. Compile it with the installed preprocessor and get a neat and clean CSS file.

Popular CSS Preprocessors:

1. SASS (Need to installed Rubi first) 2. LESS (A javascript framework Node.js should be installed) 3. Stylus (Can be installed as Node.js package)

How to write a CSS preprocessed code?

To write a preprocessed code for SASS, LESS or STYLUS you’ll need a code editor. Although any programming code can be written in even notepad but the programmers want a good editor that can highlight the syntaxes of used language. You can use eclipse (the popular code editor has syntax highlighter plug-in for most of the programming languages).  Learn and understand the syntaxes of preprocessors you are using by their documentations and start writing your code.

Compile Code With Installed Preprocessor:

After writing the preprocessed code, provide it to the compiler (wherever you installed it), let it process the code and get the old traditional CSS file that you have been writing for years. Compilation can be done in two basic ways and depends on which you love the most.

1.  Compilation On Local System: This approach has an idea to write SASS, LESS or STYLUS code on your local PC (It may be windows, linux or MAC) , run the compiler installed in the same machine that converts it to standard CSS code and use these CSS files in your theme or application. You can compile the preprocessed files both manually or automatically. You get the command line compiler by default when install the preprocessor. But if you are not so technical and don’t know using command prompt, there are many GUI compilers available on internet like Codekit or Less.app.  This approach is for non-programmers and I’d also prefer it for easy and fast compilation.

2. Client Side Compilation: An another approach is to compile to SASS or LESS code on your clients machine. Nothing has to be done in this process. Just put the SASS, LESS or STYLUS file on the server and include a javascript compiler  that converts your code to CSS files internally but you can think that how it can be so slow process as it compiles the code at page rendering time and makes a lot of load on the client’s browser.

So I think you have got a basic idea about CSS Processors and go through the following links to know about individuals.

1. Getting Started with Sass: Installation and the Basics 2. LESS CSS – Beginner's Guide 3. Getting Started With Stylus All the above are most popular CSS Preprocessors being used widely now a days.]]>
http://blogaddition.com/2013/09/what-are-css-preprocessors-and-how-to-use-them/feed/ 0
What Are Sessions And How Do They Work With PHP http://blogaddition.com/2013/09/what-are-sessions-and-how-do-they-work-with-php/ http://blogaddition.com/2013/09/what-are-sessions-and-how-do-they-work-with-php/#comments Fri, 20 Sep 2013 11:01:48 +0000 Manish Jangir http://blogaddition.com/?p=418 What Are Sessions And How Do They Work With PHP

What Are Sessions And How Do They Work With PHP

Hi Friends, I've come back after a long time on your blogaddition. Actually I couldn't write due to some of my technical works (was busy with developing my new video website way2clip.com) but now I've decided to be regular on it and write as much as possible for my readers. Today I'm not writing a programming tutorial with any kind of source coding but this post will clear all the confusions about "what are session and how do they work". I've used the phrase "Work with PHP" that means sessions are managed with each web programming or scripting language but in this article I'll talk only about Sessions In PHP.

What Are Sessions And How Do They Work With PHP

The only thing about sessions most of the programmers (not talking about experts because I'm not an expert also) know is that sessions are server side storage system. Yes, there is no any doubt but is it enough to know about sessions? People who prepare their technical interviews never read full about sessions and not be able to give the proper information about them. Some people relate sessions completely with cookies but it's not. I'll elaborate anything that how session are related with cookies and not completely dependent on them. So take a breath and start reading about... :P :)

What Are Sessions??

A logical approach that let any application store a huge amount of data on server side and make this available through out the whole application, is called session. Sessions are not any language specific but can be used in any programming logic. Haven't got??. Sessions are some kind of data storage files located on the server (usually php/tmp directory on server and can be configured also in PHP.INI file) that are used to retain the stored data on each HTTP request a client makes for. For example, suppose, you want your users to be authenticated on your application in order to view certain web pages by requiring them to provide their user identity (username and password). Does it make sense as if your users send their identity with each page url and let the application authenticate them for that particular web page?? They will abuse both you and your worst application.

Sessions Come In The Action Here

Is it not pretty good, if we authenticate our users only once at the login time and then store their common information in a particular file (session file) for a certain time period (depends on your configuration). Creating sessions make our application very much flexible and secure as the users don't need to put their user identity in the page url or in hidden inputs again and again.

How Sessions Work With PHP

I know some of you are still confused and haven't got very much about sessions. So I explain each and everything by taking a little php source code and tell how sessions work with php applications. PHP has some session handling functions and we will use some of them in our example.

Let's have a look at the following very simple Login Example Code:

[code lang="php"] $query = mysql_query("SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'"); if($result = @mysql_fetch_object($query)) { session_start(); $_SESSION['userid'] = $result->id; $_SESSION['username'] = $result->username; $_SESSION['email'] = $result->email; } else { header("Location:login.php"); } [/code]

Create The Session Using session_start()

The very first line of above code tries to get the user from database using username and password entered by end user. If it finds this a valid user, the PHP function "session_start()" executes else redirect to login again. What does this function do? This function starts the session and creates a unique identifier for that particular session which is a random string (called session identify string or session id) of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443. A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443. At the same time a temporary cookie called PHPSESSID is also set to your user's browser to store unique session identification string. After starting the session you can store the session data using PHP's Global Session Variable $_SESSION as shown in above code.

Note: You must have to start the session on first line of each page to make the use of session globally.

How PHP Identifies And Reads Session Files?

When the browser makes any HTTP request to the server for a particular resource or web page, the request carries some HTTP Request Headers with it. Headers include the PHPSESSID cookie also that was generated during the session creation. When the request reaches at the page, session_start function (included on top of the page) starts the session and tries to generate a new unique identifier string as we discussed above but before doing this it checks if any PHPSESSID cookie is present (using $_COOKIE variable) in the http request. If it finds any then looks in server temporary directory for the file bearing that name and a validation can be done by comparing both values. After finding the valid session file for that particular session you can get all stored session variables using $_SESSION also.

Destroy The Session session_destroy()

session_destroy() is usually executes on the log out files of an application to destroy both the session cookie and session file located at server session directory. After destroying the session, your application will be no longer able to read session variables.

You should have a look at the following useful PHP Session Configuration Options that can also be customized in your PHP.INI file.

Session Cookie Options:

As we discussed above PHPSESSID is called the session cookie that helps your application to find out the session file on the server for this cookie. This is a temporary cookie (that has zero lifetime)  automatically destroyed or deleted when user closes his browser. So the user has to re-log into the application to start a new session. Basic Cookie Options For Session 1. session.use_cookies : this option specifies whether your whole application will use cookies to store the PHPSESSID on the client side (browser) or you pass it with url on each request. This option takes Boolean values (1 or 0). By default it is enabled. 2. session.use_only_cookies :  This option takes also a Boolean value and specifies whether your application will identify the session file only by using cookies or not. By default it is enabled. 3. session.cookie_lifetime : This is the lifetime (by default zero) for your PHPSESSID cookie that means it will be deleted when a browser is closed. You can increase it in seconds to prevent the session destroy on browser closing.

Garbage Collection:

PHP provides a garbage collection functionality with the function session_gc(). This function executes on each session_start() call. session_gc considers all the session data as garbage and destroys the session if no activity has been done by the user in a certain period of time. This time is 24 minutes by default and can be configured changing the option session.gc_maxlifetime value in INI file.

Important: Do not get confused with session cookie life time and garbage collection life time. Both are different to each other. Suppose you configured your garbage collection life time as 30 minutes and PHPSESSID cookie (can also changed by configuring session.name) life time as 60 minutes. A user just logged into your application and immediately closed the browser and went to take his lunch. Now when he comes back within 30 minutes and opens this browser, he will find the session as it is because he did not exceed the garbage collection life time. But if he comes after 30 minutes and opens the browser he will get session destroyed even his session cookie life time is 60 minutes. It means session garbage time has much priority than cookie life time.

PHP Session Handling Functions:

It is not necessary to have the session id in cookies as we have seen that PHP.INI has an option to configure it. You can configure session.use_cookies as 0 and store the PHPSESSID in the database for that particular user for the security reason or prevent session hijacking with XSS attacks. You can use session_set_save_handler() function to create a set of user-level storage functions.  Create your own session handling functions like sessionOpen(), sessionClose(), sessionGet() and register them in session_set_save_handler(). For example call sessionOpen() function on top of each requested page that will get the PHPSESSID value from database each time and then will identify the session file. To understand this more, search for the term "php session database handler" on google.

Information: The most common PHP interview question that is asked many times is "Will session work if cookies are disabled in the browser?" and most of the people answers this as "No". This is not absolutely correct as it depends on your session configuration in INI file whether to use cookies or not.

Enjoy.... Now I think you have gained a little knowledge about "What are sessions and how do they work".

]]>
http://blogaddition.com/2013/09/what-are-sessions-and-how-do-they-work-with-php/feed/ 1
Install Zend Framework 2 In Wamp Server on Windows http://blogaddition.com/2013/02/install-zend-framework-2-in-wamp-server-on-windows/ http://blogaddition.com/2013/02/install-zend-framework-2-in-wamp-server-on-windows/#comments Wed, 13 Feb 2013 16:47:05 +0000 Manish Jangir http://blogaddition.com/?p=377 Install Zend Framework 2 On Wamp Server

Install Zend Framework 2 In Wamp Server on Windows

I've written one another article about installing zend framework 1.12 in wamp server on windows. But before some time zend has released its new version zend framework 2.1.1 that is not has the same installation process as its previous version. Although Zend Framwork 2 installation is much easy than version 1.12 but people don't know that where to start. I'll not take your too much time to explain it. Just move to following steps and get installed zend framework 2 on your windows system. For linux (Ubuntu) system, I'll write another tutorial.

Install Zend Framework 2 On Wamp Server

Step 1: Download Zend framework 2 Application Skeleton:

Actually Zend has released an application skeleton of zend framework and uploaded it to their Github repository. This application skeleton automatically installs Zend framework 2 on your computer by using composer tool. So first you need to download this application skeleton from github repository. Download it from the github link https://github.com/zendframework/ZendSkeletonApplication

Download Zend Framework 2 Application Skeleton From Github

Step 2: Extract It In Wamp/WWW And Rename It:

Extract the downloaded zip file of skeleton in your wamp/www directory and rename it according to you. In my case, it is "zendy".

Install Zend Framework 2

Step 3: Run Composer In Command Prompt:

If you don't know about composer then I tell you what exact composer  is? Composer is a PHP dependency management tool that enables you to declare any appropriate PHP library for your project and installs them in your project by command line. So before using composer, just check weather it is installed in your computer or not. Open command prompt and type "composer" and hit enter. If you've installed composer in your computer, you'll see the following image otherwise you'll get unrecognized command message.

If composer is not installed, you'll see the following image:

If composer is not installed

Or if composer is properly installed in your computer:

If composer is installed properly

If  you don't have composer installed in your computer, then first download it from http://getcomposer.org/download/ for your windows system and install it like other software. It is approximate of 550 KB.

Installing Composer

After installation it will automatically creates the system environment variables in your computer so you can run the command "composer" from any directory in your command prompt. After installing the composer again type "composer" in cmd prompt and you'll see the command prompt image shown above.

Step 4: Install Zend Framework 2 Using Composer:

Now reach at your extracted zend directory that you downloaded from github. In my case it is D:/wamp/www/zendy. May be different in your computer. After reaching this directory, run the following two commands one by one.

php composer.phar self-update php composer.phar install

After running both the commands successfully, you'll get the following image.

Install Zend Framework 2 On Wamp

Step 5 : Run Your Zend Framework Project In Browser:

Congratulations, you've installed zend framework2 successfully in your wamp server. Restart your wamp server and open your browser and type http://localhost/zendy/public (in my case it is zendy and may be different according to you). You will get the Zend Framework Welcome page if your it has been installed successfully.

Step 6: Create Virtual Host:

If you want to run your zend framework project with appropriate local domain name,  you have to make a virtual host for your project. I've told in my post http://blogaddition.com/2012/12/create-virtual-host-in-wamp/. You can read it.

Enjoy!!!

]]>
http://blogaddition.com/2013/02/install-zend-framework-2-in-wamp-server-on-windows/feed/ 19
Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL http://blogaddition.com/2013/01/database-driven-multi-level-horizontal-css-menu-with-php-and-mysql/ http://blogaddition.com/2013/01/database-driven-multi-level-horizontal-css-menu-with-php-and-mysql/#comments Thu, 31 Jan 2013 18:22:48 +0000 Manish Jangir http://blogaddition.com/?p=361 Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

There is no doubt in the truth that A website should have a good and proper navigation from user point of view to attract more visitors. Creating css navigation using php and mysql is always a headache for php newbies. In this article I've told that how to manage a horizontal css navigation menu from a single mysql table and a small piece of PHP code. Instead of wasting your time I come to our main tutorial. Go through the following points and make your own navigation menu.

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

1. Database Table "menus":

First of all make your database table to manage the menus as shown below.

Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL

As you are seeing, the table has only four fields. First column is id of each menu that is primary key and last column is the id of parent of each menu. You'll understand yourself by seeing the structure. Although I've given the demo sql database dump in zip file.

2.  Style Sheet Or Markup (style.css) :

Just apply the following css to your navigation menu.

[code lang="css"] #cssmenu ul, #cssmenu li, #cssmenu span, #cssmenu a { margin: 0; padding: 0; position: relative; } #cssmenu { height: 49px; border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; -webkit-border-radius: 5px 5px 0 0; background: #141414; background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALElEQVQImWMwMrJi+v//PxMDw3+m//8ZoPR/qBgDEhuXGLoeYswhXg8R5gAAdVpfoJ3dB5oAAAAASUVORK5CYII=) 100% 100%; background: -moz-linear-gradient(top, #32323a 0%, #141414 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #32323a), color-stop(100%, #141414)); background: -webkit-linear-gradient(top, #32323a 0%, #141414 100%); background: -o-linear-gradient(top, #32323a 0%, #141414 100%); background: -ms-linear-gradient(top, #32323a 0%, #141414 100%); background: linear-gradient(to bottom, #32323a 0%, #141414 100%); border-bottom: 2px solid #e00f16; } #cssmenu:after, #cssmenu ul:after { content: ''; display: block; clear: both; } #cssmenu a { background: #141414; background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALElEQVQImWMwMrJi+v//PxMDw3+m//8ZoPR/qBgDEhuXGLoeYswhXg8R5gAAdVpfoJ3dB5oAAAAASUVORK5CYII=) 100% 100%; background: -moz-linear-gradient(top, #32323a 0%, #141414 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #32323a), color-stop(100%, #141414)); background: -webkit-linear-gradient(top, #32323a 0%, #141414 100%); background: -o-linear-gradient(top, #32323a 0%, #141414 100%); background: -ms-linear-gradient(top, #32323a 0%, #141414 100%); background: linear-gradient(to bottom, #32323a 0%, #141414 100%); color: #ffffff; display: inline-block; font-family: Helvetica, Arial, Verdana, sans-serif; font-size: 12px; line-height: 49px; padding: 0 20px; text-decoration: none; } #cssmenu ul { list-style: none; } #cssmenu > ul { float: left; } #cssmenu > ul > li { float: left; } #cssmenu > ul > li:hover:after { content: ''; display: block; width: 0; height: 0; position: absolute; left: 50%; bottom: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #e00f16; margin-left: -10px; } #cssmenu > ul > li:first-child > a { border-radius: 5px 0 0 0; -moz-border-radius: 5px 0 0 0; -webkit-border-radius: 5px 0 0 0; } #cssmenu > ul > li:last-child > a { border-radius: 0 5px 0 0; -moz-border-radius: 0 5px 0 0; -webkit-border-radius: 0 5px 0 0; } #cssmenu > ul > li.active > a { box-shadow: inset 0 0 3px #000000; -moz-box-shadow: inset 0 0 3px #000000; -webkit-box-shadow: inset 0 0 3px #000000; background: #070707; background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALklEQVQImWNQU9Nh+v//PxMDw3+m//8ZkNj/mRgYIHxy5f//Z0BSi18e2TwS5QG4MGB54HL+mAAAAABJRU5ErkJggg==) 100% 100%; background: -moz-linear-gradient(top, #26262c 0%, #070707 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #26262c), color-stop(100%, #070707)); background: -webkit-linear-gradient(top, #26262c 0%, #070707 100%); background: -o-linear-gradient(top, #26262c 0%, #070707 100%); background: -ms-linear-gradient(top, #26262c 0%, #070707 100%); background: linear-gradient(to bottom, #26262c 0%, #070707 100%); } #cssmenu > ul > li:hover > a { background: #070707; background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAxCAIAAACUDVRzAAAAA3NCSVQICAjb4U/gAAAALklEQVQImWNQU9Nh+v//PxMDw3+m//8ZkNj/mRgYIHxy5f//Z0BSi18e2TwS5QG4MGB54HL+mAAAAABJRU5ErkJggg==) 100% 100%; background: -moz-linear-gradient(top, #26262c 0%, #070707 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #26262c), color-stop(100%, #070707)); background: -webkit-linear-gradient(top, #26262c 0%, #070707 100%); background: -o-linear-gradient(top, #26262c 0%, #070707 100%); background: -ms-linear-gradient(top, #26262c 0%, #070707 100%); background: linear-gradient(to bottom, #26262c 0%, #070707 100%); box-shadow: inset 0 0 3px #000000; -moz-box-shadow: inset 0 0 3px #000000; -webkit-box-shadow: inset 0 0 3px #000000; } #cssmenu .has-sub { z-index: 1; } #cssmenu .has-sub:hover > ul { display: block; } #cssmenu .has-sub ul { display: none; position: absolute; width: 200px; top: 100%; left: 0; } #cssmenu .has-sub ul li { *margin-bottom: -1px; } #cssmenu .has-sub ul li a { background: #e00f16; border-bottom: 1px dotted #ec6f73; filter: none; font-size: 11px; display: block; line-height: 120%; padding: 10px; } #cssmenu .has-sub ul li:hover a { background: #b00c11; } #cssmenu .has-sub .has-sub:hover > ul { display: block; } #cssmenu .has-sub .has-sub ul { display: none; position: absolute; left: 100%; top: 0; } #cssmenu .has-sub .has-sub ul li a { background: #b00c11; border-bottom: 1px dotted #d06d70; } #cssmenu .has-sub .has-sub ul li a:hover { background: #80090d; } [/code]

3. PHP Script (index.php):

This is the main PHP file that will fetch the menus from database and show them in your navigation menu using while loop. The script is written for 3 Level CSS menu. You can extend it for nth level by running the loop n times as it is.

[code lang="php"] <?php //database connection $dbname = 'csc'; $link = mysql_connect("localhost","root","") or die("Couldn't make connection."); $db = mysql_select_db($dbname, $link) or die("Couldn't select database"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL</title> <link type="text/css" rel="stylesheet" href="styles.css" /> </head> <body> <h2>Database Driven Multi-Level Horizontal CSS Menu With PHP And MYSQL</h2> <div style="width:728px;margin:auto;"> <div id='cssmenu'> <ul> <?php function query($parent_id) { //function to run a query $query = mysql_query ( "SELECT * FROM menus WHERE parent_id=$parent_id" ); return $query; } function has_child($query) { //This function checks if the menus has childs or not $rows = mysql_num_rows ( $query ); if ($rows > 0) { return true; } else { return false; } } function fetch_menu($query) { while ( $result = mysql_fetch_array ( $query ) ) { $menu_id = $result ['id']; $menu_name = $result ['menu_name']; $menu_link = $result ['menu_link']; echo "<li class='has-sub '><a href='{$menu_link}'><span>{$menu_name}</span></a>"; if (has_child ( query ( $menu_id ) )) { echo "<ul>"; fetch_menu ( query ( $menu_id ) ); echo "</ul>"; } echo "</li>"; } } fetch_menu (query(0)); //call this function with 0 parent id ?> </ul> </div> </div> </body> </html> [/code]

The tutorial is only for making you understand that what is happening. Otherwise you can download the zip file given above and implement it in your website. Just by changing the database connection properties and change your menu names and their links in database table. I hope you enjoyed the tutorial. Waiting for your comments.

Note: The same code can be used for both horizontal and vertical css menus.

]]>
http://blogaddition.com/2013/01/database-driven-multi-level-horizontal-css-menu-with-php-and-mysql/feed/ 18
Dynamically Add Remove Text Box Using Jquery http://blogaddition.com/2013/01/dynamically-add-remove-text-box-using-jquery/ http://blogaddition.com/2013/01/dynamically-add-remove-text-box-using-jquery/#comments Sat, 26 Jan 2013 05:12:33 +0000 Manish Jangir http://blogaddition.com/?p=352 Dynamically Add Remove Textboxes Using Jquery

Dynamically Add Remove Text Box Using Jquery

In this tutorial, I've written a small piece of code in jquery that will help the people who are having an issue of populating text boxes dynamically with "Add More" button in a form. I've used jquery UI also in this code to make a bounce or jumping effect when each text box is populated with add button. You can remove any text box any time by hitting remove icon given with them. To understand the better, you can view the demo and download the code given in zip file.

Dynamically Add Remove Text Box Using Jquery

Dynamically Add Remove Text Box Using Jquery
Basic Markup Or Style Sheet [code lang="css"] body{ font-family:arial; color:#666; } img{ cursor:pointer; } .txt_div{ float:left; width:300px; margin-bottom:10px; } .left{ float:left; width:250px; } .right{ float:right; width:40px; padding-top: 11px; } form input{ border:2px solid #dadada; border-radius:7px; font-size:20px; padding:5px; width:250px; } input:focus { outline:none; border-color:#9ecaed; box-shadow:0 0 10px #9ecaed; } form .button{ background: -moz-linear-gradient(top, #00b7ea 21%, #009ec3 76%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(21%,#00b7ea), color-stop(76%,#009ec3)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #00b7ea 21%,#009ec3 76%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #00b7ea 21%,#009ec3 76%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #00b7ea 21%,#009ec3 76%); /* IE10+ */ background: linear-gradient(to bottom, #00b7ea 21%,#009ec3 76%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00b7ea', endColorstr='#009ec3',GradientType=0 ); /* IE6-9 */ color:#DFE9EC; border:none; cursor:pointer; padding:7px; } [/code] This is the basic markup or style sheet of the page that will make attractive the text boxes and buttons. You can change it accordingly. Jquery Script [code lang="javascript"] $(document).ready(function(){ var id = 2,max = 8,append_data; //max is the limit of textboxes /*If the add icon was clicked*/ $(".add").live('click',function(){ if($("div[id^='txt_']").length $(this).remove(); //remove the add icon from current text box var append_data = '</pre> <div id="txt_'+id+'" class="txt_div" style="display: none;"> <div class="left"><input id="input_'+id+'" type="text" name="txtval[]" /></div> <div class="right"><img class="add" src="add.png" alt="" /> <img class="remove" src="remove.png" alt="" /></div> </div> <pre> '; $("#text_boxes").append(append_data); //append new text box in main div $("#txt_"+id).effect("bounce", { times:3 }, 300); //display block appended text box with silde down id++; } else { alert("Maximum 8 textboxes are allowed"); } }) /*If remove icon was clicked*/ $(".remove").live('click',function(){ var prev_obj = $(this).parents().eq(1).prev().attr('id'); //previous div id of this text box $(this).parents().eq(1).slideUp('medium',function() { $(this).remove(); //remove this text box with slide up if($("div[id^='txt_']").length > 1){ append_data = '</pre> <img class="remove" src="remove.png" alt="" /> <pre>'; }else{ append_data = ''; } if($(".add").length < 1){ $("#"+prev_obj+" .right").html('</pre> <img class="add" src="add.png" alt="" /> <pre> '+append_data); } }); }) }); [/code] This is the main javascript code which performs the functionality of adding or removing text boxes dynamically. The maximum limit of adding text boxes is given 8 in the script. This can be changed according to your requirement. Index.html [code lang="html"] Dynamically Add Remove Textboxes Using Jquery <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> </pre> <div style="width: 800px; margin: auto; padding-top: 100px;"> <h1>Dynamically Add Remove Textboxes Using Jquery</h1> <form id="form" name="form"> <div id="text_boxes" style="width: 300px; height: auto;"> <div id="txt_1" class="txt_div"> <div class="left"><input id="input_1" type="text" name="txtval[]" /></div> <div class="right"><img class="add" src="add.png" alt="" /></div> </div> </div> <div style="clear: left;"></div> <input class="button" type="button" value="SUBMIT" /></form></div> <pre> [/code] That's all the script. You can download it also and free to modify it anytime.]]>
http://blogaddition.com/2013/01/dynamically-add-remove-text-box-using-jquery/feed/ 4
Install Node.js On Windows And Ubuntu System http://blogaddition.com/2013/01/install-node-js-on-windows-and-ubuntu-system/ http://blogaddition.com/2013/01/install-node-js-on-windows-and-ubuntu-system/#comments Tue, 22 Jan 2013 17:48:44 +0000 Manish Jangir http://blogaddition.com/?p=339 Install Node.js in windows system

Install Node.js On Windows And Ubuntu System

In the previous article you understood that what actually node.js is, if you read that. Now I'm going to tell "How to install node.js in both windows and ubuntu system". After installing it properly, we'll make a simple node program to test our installation.

Install Node.js On Windows And Ubuntu System

Install Node.js In Windows System:

A very simple and straight forward way to install node.js  in windows system is its Microsoft Installer or .msi file which can be download from node's download page. 1. Download the node.msi file from here.

Download Node.js windows installer 2. Double click and run the downloaded msi file and get installed it on your windows.

Install Node.js in windows system The Microsoft Installer of node.js installs both Node platform and NPM in your computer. NPM is Node Package Manager or module manager which helps us to install or include new modules in our node application according to the requirement. The default node installation directory in windows is C:\Program Files\nodejs.

Test Your Node.js Installation:

To check weather it is installed properly or not you can test it in command prompt. Open your command prompt from Start->Run->type cmd and hit enter. Now type node -v in cmd and hit enter. You will get the version of node.js installed on your system e.g. 0.8.17 or something else. Similarly type npm -v to test the npm installation. You will see the following screen.

Test Node.js Installation In Windows If both are OK then congratulations you've get installed node.js perfectly in your windows system.

Install Node.js On Ubuntu System:

Installing node.js on Ubuntu is not so complicated or messy as people think about it. Open the terminal and execute all the following commands one by one and wait. This depends on your internet connection speed. Within a few minutes you will be using node.js on your Ubuntu system also.

Ubuntu Commands For Node.js Installation:

sudo apt-get install python-software-properties python g++ make sudo add-apt-repository ppa:chris-lea/node.js sudo apt-get update sudo apt-get install nodejs npm

It installs current stable Node on the current stable Ubuntu. Quantal (12.10) users may need to install the software-properties-common package for the add-apt-repository command to work: sudo apt-get install software-properties-common After executing all the commands successfully, go in your default or home directory from terminal and execute the same following commands to see the installed versions of node.js and npm. $node -v $npm -v If both are OK and giving the version number of node and npm then you've successfully installed node.js on your Ubuntu computer also.

What are Node.js Modules ?

Node.js is a combinations of node packages. Actually it has a very managed module system by which we can install appropriate modules in node according to our application requirement. There are many node.js modules developed day by day by node lovers. It comes with some default core modules such as http and net. All the modules can be installed via NPM (Node Package Manager).

How to install A Node.js Module Via NPM?

To install a Node.js Module in your computer, just open command prompt (In Windows) or terminal (In Linux) and type the following command: $npm install module_name (For Linux) C:\Documents and Settings\Manish npm install module_name (For windows). Something like below:

Install Node.js Module using NPM

This will install the node module in your main node installation directory.

Write A Very Simple Node Program To Test Our Node Installation: Because this is an installation tutorial of node, so instead of taking a very complex example, I'm making a simple application to verify your Node installation. Follow the given steps below: 1. Create a new directory "nodeapp" in C: drive. You can take the appropriate name and create it in any location where you want to put your node application. But make sure you can easily reach this directory through command prompt. 2. Now create a new javascript file app.js in this directory and paste the following code in the file. Save it and come to command prompt. [code lang="javascript"] var http = require('http'); //This includes the default http module in application http.createServer(function (req, res) { //this creates the server running on appropriate port res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); //This writes "hello world" in the page. }).listen(8080, 'localhost'); //write on what port you want to run the application console.log('Server is running at http://localhost:8080'); [/code] 3. Reach the directory nodeapp in command prompt and type the command "node app.js". Your console will be showing the line "Server running at http://localhost:8080" and open the url http://localhost:8080 in your browser and see what happens? You will see the page showing "Hello World". Have you noticed that there is no need of Apache Web Server to run this url in browser? That's all the magic of node.js. I'll be continue with some other complex and useful node.js applications.]]>
http://blogaddition.com/2013/01/install-node-js-on-windows-and-ubuntu-system/feed/ 0
What is Node.js And How It Works? http://blogaddition.com/2013/01/what-is-node-js-and-how-it-works/ http://blogaddition.com/2013/01/what-is-node-js-and-how-it-works/#comments Fri, 18 Jan 2013 17:47:56 +0000 Manish Jangir http://blogaddition.com/?p=330 What is Node.js And How It Works?

What is Node.js And How It Works?

Till today, you all have used javascript on client side only in your web applications for validation purpose, event handling functions or something else. Have you tried it on server side before ever?? Now you must be thinking, what nonsense I'm talking about. I'm just not joking because it's time to do something crazy. After a lot of research and understanding the data structure of all scripting languages, Ryan Dahl decided to design such a server side software system that can run on Google's V8 javascript engine and be able to create highly scalable, event driven and real time applications. It was named as node.js. Now you are worrying about "what is real time application". Before we move on further detail about node.js, I'd like to introduce you with Real Time Applications.

What is Node.js And How It Works?

What are Real Time Applications??

Instead of letting you read the garbage definition of it, I focus on an effective example. Suppose you open your facebook account in two different browsers (Mozilla Firefox and Google Chrome). You've started chat in Mozilla Firefox and have sent a number of messages to the end user. Have you noticed that after hitting the enter key on chat box, the same message immediately appears in Google chrome chat box also without having a time delay. This is real time application in which the user does not need to wait for a single second to get the response from server.Real time applications is same as the cricket game in which you throw a ball and someone catch it in real time instead of waiting. Other examples of real time applications are live chatting, Voice Over Internet Protocol (VOIP), Online Games where scores get update before blinking our eyes.

So it was all about real time applications. Now come to Node.js. Actually Node.js is a server side javascript whose all programs are written in pure javascript. All browsers and every web application programmer are much familiar with javascript. By using javascript on both client and server side the browser reduces impendence mismatch created between two different programming environment.

Most of the web developers who haven't heard about node.js, try to make a chat application using ajax and mysql that is totally nonsense. In this chat app, the message is stored in mysql table first and then displayed on the chat box of end user by ajax. The chat box calls ajax in every 1 second and fetch the recently sent messages from database. This makes the application so slow that increases the load on database server also. A highly scalable chat application can be developed using node.js and socket.io module that communicates browser to browser directly and pushes a message intensely on the browser.

Node.js Modules:

Although Ryan Dahl has given us a server side javascript platform to work with but he can't reserve his whole life for node.js development. Actually node.js comes with a package manager or module manager by which we can install and use it's modules as our application requirement. There are many modules have been developed by crazy node.js developers. We can find them on github repository.

Benefits of Node.js:

1. As javascript is the most popular language, So everyone can create node.js programs. 2. As we are using javascript on both client and server side in our web application so the browser reduces the impendence mismatch between two different programming environments. 3. On a single process, Node.js can handle thousands of connections. 4. It creates it's own http server in run time that may be run on appropriate port defined by you in the program. So no need to install apache or some another. This was a brief about node.js and I know you haven't got very much about Node.js by reading this article but you will understand it very good after reading some further articles that I'm writing. In the next article I'm will be telling you about "how to install node.js on windows and linux system".]]>
http://blogaddition.com/2013/01/what-is-node-js-and-how-it-works/feed/ 0