Sunday, 22 September 2013

Simple Pagination using jquery,mySql and PHP



In this post we are going to learn about pagination using jQuery,MySQL and PHP.This is very simple
tutorial.It has four files which are as below.

(1) config.php file
    - For the database connection details.

(2) index.php file
    - Main file that display the result to the user.

(3) data.php file
    - File having code to fetch the data from the table.

(4) pagination.js file
    - Javascript file for acting as a data controller


Download Full Source

Create Database table


CREATE TABLE IF NOT EXISTS `users`(

 `id` int(10) NOT NULL AUTO_INCREMENT,

 `FirstName` varchar(200) NOT NULL,

 `Middlename` varchar(200) NOT NULL,

 `LastName` varchar(200) NOT NULL,

 PRIMARY KEY (`id`) )


config.php file

Change the values of hostname,username,password and database name

<?php
$mysql_hostname = "localhost"; 
$mysql_user = "root"; 
$mysql_password = ""; 

$mysql_database = "test"; 

$con = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps error! occurred");

mysql_select_db($mysql_database, $con) or die("Opps error! occurred");
?>

index.php file

Note : Here we are using select count(*) from table instead of select * from table
because Letting MySQL do the counting is SIGNIFICANTLY faster,as it only counts the entries rather than parsing all data,AND only returns a very small block of data :)


<?php
include('config.php');

$per_page = 3; 



//getting number of rows and calculating no of pages

$sql = "select count(*) from users";

$result = mysql_query($sql);

$count = mysql_fetch_row($result);

$pages = ceil($count[0]/$per_page);

?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pagination.js"></script>

<div id="content" ></div>
<table width="800px">
<tr><Td>
<ul id="pagination">
<?php
    //Show page links
    for($i=1; $i<=$pages; $i++)
    {
echo '<li id="'.$i.'">'.$i.'</li>';
    }
?>
             </ul>
   </Td>
     </tr></table>
<div id="loading" ></div>

data.php file

<?php
include('config.php');

$per_page = 3; 

if($_GET)

{

$page=$_GET['page'];

}



//getting table contents

$start = ($page-1)*$per_page;
$sql = "select * from users order by id limit $start,$per_page";
$rsd = mysql_query($sql);
?>

<table id="tbl">
<th><b>Id</b></th>
<th><b>FirstName</b></th>
<th><b>MiddleName</b></th>
<th><b>LastName</b></th>
<?php
while($row = mysql_fetch_array($rsd))
{
$id    = $row['id'];
$fname = $row['FirstName'];
$mname = $row['Middlename'];
$lname = $row['LastName'];
?>
<tr>
<td><?php echo $id; ?></td>
<td><?php echo $fname; ?></td>
<td><?php echo $mname; ?></td>
<td><?php echo $lname; ?></td>
</tr>
<?php
} //End while
?>
</table>

pagination.js file


$(document).ready(function(){

//Loading Image Display

function Display_Load()

{

   $("#loading").fadeIn(100);

$("#loading").html("<img src='loading.gif' />");

}

//Hide Loading Image

function Hide_Load()
{
$("#loading").fadeOut('slow');
};

   //Default Starting Page Results
   
$("#pagination li:first").css({'color' : '#FF0084','border' : 'none'});
$("#content").load("data.php?page=1", Hide_Load());

//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});

//Loading Data
var pageNum = this.id;
$("#content").load("data.php?page=" + pageNum, Hide_Load());
});
});



Download Full Source

Tuesday, 17 September 2013

Add Read More Link When Someone Copy Paste Your Content


Few days before when i was surfing for the latest news and I noticed(you may have also noticed that) if you copy and paste any text from the site a reference link is added at the bottom of the copied content,indicating the source from where you have copied that. 

I was surprised and was sure that i have copied only content then how that link also copied and then tried to figure out how it happened and how to do it. I figured out that they use a service called "Tynt". Ya its cool but who wanted to use it.After all we are developers so i just wanted to see if we could make it happen by using JavaScript and hurray it was possible. 

One function needs to grab the copied selection, tack on a copyright notice and then add the two to the clipboard. 


<script type="text/javascript">

function addLink() {

     var body_element = document.getElementsByTagName('body')[0];

     var selection;

     selection = window.getSelection();

var pagelink = "<br /><br />
Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a>"; 
     var copytext = selection + pagelink;
     var newdiv = document.createElement('div');
     newdiv.style.position='absolute';
     newdiv.style.left='-99999px';
     body_element.appendChild(newdiv);
     newdiv.innerHTML = copytext;
     selection.selectAllChildren(newdiv);
     window.setTimeout(function() {
     body_element.removeChild(newdiv);
     },0);
}
document.oncopy = addLink;
</script>


Demo : Just copy the following para and paste it in any editor.You will see an extra link for read more link is added at the bottom.


Note: Not Compatible with IE.

Sunday, 15 September 2013

Add Meta Description and Meta Keywords in opencart



In this tutorial we will see how to add meta description and meta keywords in opencart.Just follow the steps given below.

Step 1 : Add new fields "Meta Keywords" and "Meta Description" in the database

In order to add Meta Keywords and Meta Description in pages we first have to add Meta Description and Meta Keywords  fields into the database in the table called as information_description. Simply Run the following query:

ALTER TABLE `information_description` ADD `meta_description` VARCHAR( 255 ) NOT NULL, ADD `meta_keywords` VARCHAR( 255 ) NOT NULL

Note: please consider if you have database prefix or not.(Example: oc_) if so then use "oc_information_description.


Step 2 : Add two Text boxes in admin panel


Go to : admin/view/template/catalog/information_form.tpl file and search for the $entry_description code and insert the code given below just before it:

<tr>
   <td><?php //echo $entry_meta_description;?>Meta Description</td>
   <td><textarea  name="information_description[<?php  echo $language['language_id'];?>][meta_description]" cols="50"  rows="6"><?php echo isset($information_description[$language['language_id']]) ? $information_description[$language['language_id']]['meta_description'] : ''; ?>
</textarea>
    </td>
</tr>



<tr>
    <td><?php //echo $entry_meta_keywords; ?>Meta Keywords</td>
    <td><textarea  name="information_description[<?php  echo $language['language_id'];?>][meta_keywords]" cols="50"  rows="6"><?php echo isset($information_description[$language['language_id']]) ? $information_description[$language['language_id']]['meta_keywords'] : ''; ?>
  </textarea>
   </td>
</tr>

Step:3 Add new fields in the model.


Go to admin/model/catalog/information.php. Search for below code  in the addInformation() function.

$this->db->query("INSERT INTO " . DB_PREFIX . "information_description SET information_id = '" . (int)$information_id . "', language_id = '" . (int)$language_id . "', title = '" . $this->db->escape($value['title']) . "', description = '" . $this->db->escape($value['description']) . "'");

replace it with  code given below:

$this->db->query("INSERT INTO " . DB_PREFIX . "information_description SET information_id = '" . (int)$information_id . "', language_id = '" . (int)$language_id . "', title = '" . $this->db->escape($value['title']) . "', description = '" . $this->db->escape($value['description']) . "', meta_description = '".$this->db->escape($value['meta_description'])."', meta_keywords = '".$this->db->escape($value['meta_keywords'])."'");

Now, in the same function addInformation();search for this code,

if ($data['keyword']) {
$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'information_id=" . (int)$information_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
}

replace it with code given below:

if ($data['keyword']) { $this->db->query("INSERT INTO " . DB_PREFIX . "information_description SET information_id = '" . (int)$information_id . "', language_id = '" . (int)$language_id . "', title = '" . $this->db->escape($value['title']) . "', description = '" . $this->db->escape($value['description']) . "', meta_description = '".$this->db->escape($value['meta_description'])."', meta_keywords = '".$this->db->escape($value['meta_keywords'])."'"); }

Now find editInformation() function and search the following code,

$this->db->query("INSERT INTO " . DB_PREFIX . "information_description SET information_id = '" . (int)$information_id . "', language_id = '" . (int)$language_id . "', title = '" . $this->db->escape($value['title']) . "', description = '" . $this->db->escape($value['description']) . "'");

and replace the code with  code given below:

$this->db->query("INSERT INTO " . DB_PREFIX . "information_description SET information_id = '" . (int)$information_id . "', language_id = '" . (int)$language_id . "', title = '" . $this->db->escape($value['title']) . "', description = '" . $this->db->escape($value['description']) . "', meta_description = '".$this->db->escape($value['meta_description'])."', meta_keywords = '".$this->db->escape($value['meta_keywords'])."'");

Now in getInformationDescriptions() function search for the below code.

foreach ($query->rows as $result) {
            $information_description_data[$result['language_id']] = array(
                'title'       => $result['title'],
                'description' => $result['description']
            );
        }

replace it with code given below.

foreach ($query->rows as $result) {
            $information_description_data[$result['language_id']] = array(
                'title'       => $result['title'],
                'description' => $result['description'],
                 'meta_description' => $result['meta_description'],
                'meta_keywords' => $result['meta_keywords']
            );
        }

Step:4 open /catalog/controller/information/information.php file and in index() function search for the code

if ($information_info) {
$this->document->setTitle($information_info['title']);

Simply add the following two lines just below it.

$this->document->setDescription($information_info['meta_description']);
$this->document->setKeywords($information_info['meta_keywords']);

now it will look like this,

if ($information_info) { $this->document->setTitle($information_info['title']);
$this->document->setDescription($information_info['meta_description']);
$this->document->setKeywords($information_info['meta_keywords']);

Final Step :

Go to Admin side and open catalog > information and open any page.You will find two new fields meta Description and Meta Keywords are added.Enter the details and Go to Front Side and check the page source by pressing Ctrl+U.You will find entered details withing meta description and Meta keywords tags.

Sunday, 8 September 2013

Decrease Page Loading Time



Today we are going to talk about how to improve web page speed or how to decrease the loading time.

Generally Users are enamored with speedy websites, and if  any  site responds very  slowly, visitors lose their patience and are less likely to come back.

Improvement in page loading speed is not only useful for the site users but also for the search engine rankings as well. Google announced that from now website speed will also be included in their search ranking algorithms.

So below are some of the solutions which help you in decreasing web page load time.

1. Website’s  Current Speed Analysis


The very first thing that is required  is to analyze your current web  page speed. This will allow you to track improvements and ensure that changes mae by you improves page load times.

So many free tools are available to check how much time your site takes to load.Below are a few of them:

Pingdom :  provide an easy  site speed test that which shows the way a page is loaded in a web browser.
Web Page Test : Tool for checking your site’s  speed and performance in different browsers.
Page Speed :  An open source Firefox add-on which helps you assess the performance of your web pages. Suggestions are also available on how to fix the issues.

2. Image optimization

Its also important to know when to use the appropriate file format for your images. Using a different file format may dramatically decrease the file size of an image.

PNG    :  Choice when high quality transparent images are required.
JPEG  :  Great for images with lots of colors and details like photographs.
GIF     : Ideal for the images having very few colors.Example: logos.

Some useful links:

•    Web Designer’s Guide to PNG Image Format
•    8 Excellent Tools for Optimizing Your Images
•    The Comprehensive Guide to Saving Images for the Web
•    JPEG 101: A Crash Course Guide on JPEG


3. Never  Scale Down Your Images 

Never use a larger image than you need because width and height attributes of <img> elements can be set in HTML.

Say for Example, You need a 100x100px image but you have a 700x700px image, in this case never use the big image directly,Use of an  image editor like Photoshop is advisable in order to resize the image to the required dimensions. This will lower the file size of the image, so helps you to decrease page loading times.

4. Put Stylesheet References at the Top

Putting stylesheet references to the <head> section helps pages feel like it is loading faster.This is because it allows pages to render the styles progressively. Plus, it does not hurt that it is the W3C standard.

5. By Adding References of Script at the Bottom

At the same time, browsers can only download two components per hostname. If have added you scripts in the top,then on the initial loading of the page it would block anything else below it.User feels like the page is loading slower.

In order to avoid this, put script references as far down the HTML document as possible, preferably right before the closing <body> tag.

6. Keep CSS and Javascripts in an External Files

If your placing javascript and css directly in HTML document, they are downloaded every time when an HTML document is requested. This, increases the size of the HTML document and then, doesn’t take advantage of browser caching.

Its good practise to place your css and javascript in external files which makes the site easier to maintain and update.

7. HTTP Requests minimization

In general scenario what happen,when you visit any new web page, most of the page-loading time is spent for downloading components of that page (e.g. images, stylesheets, and scripts).

If you minimize the number of requests a web page needs to make, it will load faster. To reduce HTTP requests for images, one simple thing you can do is to use CSS sprites so that multiple images can be combined.

Multiple stylesheets and JavaScript libraries can be combined to reduce the number of HTTP requests.

8. Web Pages caching

If you using a CMS(content management system) that dynamically generates your web pages, you should cache database queries and your web pages so that the strain on your server can be decreased  and it speed up page rendering times also.

Advantage of cached page is that static version of it saved and delivered to the user instead of recreation of it every time when the request is made.

Note: Drupal core has native caching.

For Wordpress please check,
WP Super Cache
W3 Total Cache
-  WordPress codex entry on optimizing/caching WordPress

Below are links from where you can learn more about caching.

http://www.mnot.net/cache_docs/
http://en.wikipedia.org/wiki/Web_cache


Sunday, 25 August 2013

How to open Galaxy S4 configuration emulator

How to open Galaxy S4 AVD:

Google has not released Galaxy S4 configured built in emulator. It is not available in android SDK. So it is very tough to test app in this configuration basically for who does not have the real Galaxy S4 device. I don’t have this device but I like to test my app in Galaxy S4. In this tutorial I am trying to help to create Galaxy S4 configuration emulator. 
 
Caution: As Galaxy S4 is not available now in android SDK so it will not give you proper feel and behavior.
 
To get the same behavior it is recommended to use the real device. S4 device screen is HD so your
desktop or laptop screen will have to be HD resolution capability if at least you want to create S4 avd.
 
How to open Galaxy S4 AVD:
At first click on the Virtual device manager and set the following attributes like the image below.
 
Now you are ready to run your Galaxy S4 AVD.
 
Problems in opening Galaxy S4 AVD: I have seen many developers complain that they did not able to open S4 configuration AVD in their laptop. It happened may be for your pc configuration (I am not sure) orr ram unavailability. I recommend that try to use real device for testing purpose.
 

Thursday, 22 August 2013

5 Best tools for Web Developers And Designers



Web designing and web development are two professions that are highly on demand in today’s age and time. With the help of the several tools, web designers and developers are in an advantageous position to create the best looking sites today.

Dreamweaver: One of the most trusted web development tools that have been with the developers for a long time is Dreamweaver. It gives users a one-stop-shop feel to designers who can use the tool to create almost any kind of site.


Photoshop: Photoshop needs no introduction. From designing attractive logos to creating web templates, this is a must-have tool for all.



CoffeeCup Free HTML Editor: CoffeeCup Free HTML Editor is a tool that is perfect for beginners. It has all the basic HTML requirement but a few essential tools are missing such as CSS menu, FTP upload etc.


Brackets: Brackets is an open source code editor which can be used by web developers to write HTML, CSS and JavaScript-based code.



Foundation by Zurb: Foundation is an advanced responsive tool that can be effectively used to create websites especially designed for small devices. Foundation also helps in improving codes as one writes them.


Author Bio:
This Post is contributed by ValueCoders, a leading IT Outsourcing company, specialized inweb and mobile development. One can Hire HTML Programmers here for excellent HTMLdevelopment services. 

Tuesday, 20 August 2013

Multiple Images Upload in CakePHP



In this post we will see how to uload multiple images in cakephp.I am going to show the additional code for multiple image handling for both the action Add and Edit.What all you need is to simply copy paste in your application according to needs.

My table : posts

CREATE TABLE `posts` (
`id` int(10) NOT NULL AUTO_INCREMENT,

`title` varchar(200) NOT NULL,

`body` text NOT NULL,

`image1` varchar(200), 

`image2` varchar(200), 

`image3` varchar(200),
PRIMARY KEY (`id`)
)

As you can see what are the fields of my 'posts' table.I have three fields for the images.Example: image1,image2,image3 etc.You may have different fields. Add the code given below for multiple image handling.

My uploaded images are stored in  app/webroot/img/uploads/posts  folder.I have one default image called 'no-icon.jpg' in the same folder which will be shown if the correct image is not available or in case of NULL value.

Controller : PostsController.php


Add Function

public function add() {

$this->Post->create();

if ($this->request->is('post')) {



// Image Handling code START //////

for($i=1;$i<4;$i++)

{

if(empty($this->data['Post']['image'.$i]['name'])){
unset($this->request->data['Post']['image'.$i]);
}
if(!empty($this->data['Post']['image'.$i]['name']))
{
$file=$this->data['Post']['image'.$i];
$ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . mktime().$file['name']);
$this->request->data['Post']['image'.$i] = mktime().$file['name'];
}
}
}
// Image Handling code END //////

  if ($this->Post->save($this->request->data)) 
  {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else 
{
$this->Session->setFlash('Unable to add your post.');
}
}
}


Edit Function

public function edit($id=null){

if(!$id)

{

throw new NotFoundException(__('Invalid Post'));

}



$post=$this->Post->findById($id);
if(!$post)
{
throw new NotFoundException(__('Invalid Post'));
}
if(!empty($this->data))
{
$this->Post->id=$id;
                                
// Image Handling code START //////
for($i=1;$i<4;$i++)
{
if(empty($this->data['Post']['image'.$i]['name'])){
unset($this->request->data['Post']['image'.$i]);
}
if(!empty($this->data['Post']['image'.$i]['name']))
{
if(file_exists("img/uploads/posts/".$this->data['Post']['hiddenimage'.$i])){
  unlink("img/uploads/posts/".$this->data['Post']['hiddenimage'.$i]);
    }
$file=$this->data['Post']['image'.$i];
$ary_ext=array('jpg','jpeg','gif','png'); //array of allowed extensions
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
if(in_array($ext, $ary_ext))
{
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/uploads/posts/' . mktime().$file['name']);
$this->request->data['Post']['image'.$i] = mktime().$file['name'];
}
}
}
        // Image Handling code END //////
if($this->Post->save($this->request->data))
{
$this->Session->setFlash('Your Post has been Updated');
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash('Unable to update your post.');
}
}
if(!$this->request->data){
$this->request->data=$post;
}
}


I can't post all the code of view files so for that please Download the complete source code from the below link.

Download Full Source