Sunday, November 22, 2009

Finding Database Size using php & mysql

The dbsize of mysql can be retrieved using the query "show table status'.

Follow the steps to find the DB size
Step 1:
Getting connection with the databse
<?php

$db = mysql_connect("hostname", "username","password"); //getting the mysql db connection by passing correct hostname,username and passowrd
mysql_select_db("dbname",$db); //there we pass the db name for which we want the size to be calculated. This is like calling "use dbanme";
?>
Step 2:
The dbsize is the total of Index_length and Data_lenth columns of all the tables present in the database selected.
We will find the size with the below function


<?php
{
$sql = "SHOW TABLE STATUS";
$result = mysql_query($sql); // This is the result of executing the query
while($row = mysql_fetch_array($result))// Here we are to add the columns 'Index_length' and 'Data_length' of each row
{
$total = $row['Data_length']+$row['Index_length'];
}
echo($total); // here we print the file size in bytes
}
?>

Wednesday, September 2, 2009

SEO Don’ts

Bad Techniques:

Bad search engine optimization techniques can get you blacklisted from a search engine. Some techniques that are considered spam are cloaking, invisible text, tiny text, identical pages, doorway pages, refresh tags, link farms, filling comment tags with keyword phrases only, keyword phrases in the author tag, keyword density to high, mirror pages and mirror sites.
While these techniques might work to give you a higher ranking for short time in the long run they will hurt you.
Google has a good article on Google information for webmasters that is very imformative if you are considering Getting a SEO Company to so work on your website.

A Few SEO Don’ts — Flash and Splash


Along with any list of Do’s come the Don’ts. As far as SEO is concerned, two of these items are splash pages (often consisting of a flash animation) and all flash web sites.

Yes, flash is pretty! Full flash web sites can actually be amazing to look at — their own bit of interactive artwork. But unfortunately the search engines don’t get along well with Flash. Although there is talk of possible advancement in this area, for the most part the search engines cannot read Flash.

All that great content that you wrote for your site will not be seen by the search engines if it’s embedded into a Flash web site. As far as the search engines are concerned, your all flash web site might as well be invisible. And if the search engines can’t see your site content, a good chunk of potential customers will miss out on what you have to offer, too.

Equally as “pointless” are splash pages. Once very popular, the splash page should no longer be an important feature of any site. While splash pages used to serve as an introduction into a web site (often with a flash animation), it is no longer seen as helpful, and often times might actually annoy visitors.

For one — it’s an extra click to get into your content. Worse is when you don’t give a “skip intro” option or set of links into your main site content — because you’re essentially forcing your visitors to sit through the full animation. If you’re lucky, this will only annoy them… if not — they’ll just leave without giving your main web site a shot. And without an html link pointing into your site, the search engines have no way to continue either (unless you made use of a sitemap.xml file — but still…)

A good alternative to both issues is to make use of a flash header. There’s no problem to include a flash animation at the top of your main site, or as a feature within the content area, etc. Because this is an addition to your web site, as opposed to a full separate element.

More SEO tips - The do’s and do not’s

  • Do not target common keywords like “shop” or “design”
  • Do not copy any content from other pages
  • Add new content from time to time to keep your site on top
  • Monitor and analyze your keywords performance and study your competitor
  • Try to avoid flash and scripts to keep your code clean
  • Use not more than 5 to 7 words for your meta keywords
  • Use unique and relevant meta keywords for every single page
  • Create landing pages, optimized for specific keywords
  • Don’t spam your meta tags with keywords, focus on your main keywords
  • Provide unique and useful content. Seriously, this is crucial!
  • Use text for your navigation and not images
  • Integrate a blog for fresh content and social marketing possibilities
  • Once again, take your time researching the right keywords for your site
Don’t wait too long to implement SEO. Whether you’re launching a new Web site or upgrading your current site, SEO considerations should be part of the discussion from day one.

Don’t make your web site uncrawlable. This can result from an incorrect robots.txt file, having session IDs or too many variables in your URLs, using a convoluted navigation menu that spiders can’t (or won’t) follow, or developing an all-Flash, all-graphic, or all-AJAX site.

Don’t target overly general keywords. A real estate agency in Wichita has no shot at ranking for the phrase “real estate;” a lawyer in Fresno has no shot at ranking for the word “lawyer.” Optimize for relevant, specific keywords that will bring targeted traffic.

Don’t stuff keywords in your meta tags, image alt tags, etc. That is so 1996-97. Today, it’s called spam.

Don’t stuff keywords in your page footer with lightly-colored or hidden text. That is so 1998-99. Today, it’s also called spam.

Don’t have the same title element on every page. Variety is the spice of life and, combined with relevance, is a pre-requisite to avoiding duplicate content issues and Google’s supplemental index.

Saturday, August 22, 2009

Simple Encryption in PHP

Encryption using php?


A text or a password encryption can be done very easily using the functions md5() or sha1() or crypt() in php. It's a basic need to protect the password. The first step towards it is to encrypt it.

Text Encryption Using MD5 ( RSA's MD5 Message-Digest Algorithm ):


Example:

Original Text - This is test
Encrypted Text - fe1ca9859cefff19959d57aadc17187e

code:
<?php
$var = "This is test";
$enc = md5($var);
echo "Encrypted Text - $enc";
?>
On handling password, update the encrypted password in to database.
On login request, encrypt the password entered by user and compare it with the one in db.


Text Encryption Using SHA1 ( US Secure Hash Algorithm 1 ):


Example:
Original Text - This is test
Encrypted Text - 21650e52cb7a82638b93971684f6dcfceb14c9ab

code:
<?php
$var = "This is test";
$enc = sha1($var);
echo "Encrypted Text - $enc";
?>

On handling password, update the encrypted password in to database.
On login request, encrypt the password entered by user and compare it with the one in db.

Text Encryption Using Unix DES-based encryption algorithm :


Example:
Original Text - This is test
Encrypted Text - $1$tYQu2pZ5$s7mbrcnNzKFHZCrA5SXyJ/

code:
<?php
$var = "This is test";
$enc = crypt($var); //salt be automatically generated
echo "Encrypted Text - $enc";
?>

On handling password, update the encrypted password in to database.
On login request, use encrypt() as below to validate the password.
if (crypt($input, $password) == $password) {
echo "Password verified!"; }
where $input in user posted password and $password is the encrypted one in database.

Saturday, July 25, 2009

Ajax + PHP sample code

Function to create ajax object


AJAX stands for Asynchronous JavaScript and XML.

Ajax is a technology used to refresh a page content(or page area ) with out refreshing the whole page.AJAX is based on JavaScript and HTTP requests.We can use multiple ajax requestes on same page.

In the following example we are going to print some values from the server.

This function creates an ajax object. In these architecture we can use the same object for different ajax call. So multiple ajax object creation is not needed.It creates an XMLhttp object and return that object

Ajax object creation

function GetXmlHttpObject()
{
objXMLHttp = false;
try
{
objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
objXMLHttp = false;
}
}
if (!objXMLHttp && typeof XMLHttpRequest != 'undefined')
objXMLHttp = new XMLHttpRequest();
return objXMLHttp;
}

With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can receive data from the web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

All new browsers except IE5 and IE6 use the built-in JavaScript XMLHttpRequest object to create an XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).

Function to call ajax


This function calls the server page.First this function creates an ajax object by calling our function GetXmlHttpObject().

Call Ajax object

function callAjax()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
// Create a function that will receive data sent from the server
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
document.getElementById('resultdiv').innerHTML= xmlHttp.responseText;
}
}
xmlHttp.open("GET", "ajaxsample.php", true);
xmlHttp.send(null);

}
After a request to a server, we need a function to receive the data returned from the server.

The onreadystatechange property stores the function that will process the response from a server. The function is stored in the property to be called automatically.This function checks the ajax states.

Ajax States.

State Description
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

So after the 4 th state is completed, the javascript receives the result from the server.

Html file

Place the above javascript functions to the same html file

Web page


<script>
// place the above two functions here......
</script>

<form action="frmCheck" method="get">
<table width="445" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="74">&nbsp;</td>
<td width="365"><div id="resultdiv"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="button" name="btnCheck" id="button" value="Check" onClick="callAjax();"></td>
</tr>
</table>
</form>

This html file contains the form values. While clicking the button it will call the "callAjax" function .

Server page (PHP page)


The ajax request the following page and it returns the value. We can use our own code here.

Server Page - ajaxsample.php


<?php
echo "ajax sample..";
?>

After running this page shows the text 'ajax sample..' on browser.

Tuesday, May 12, 2009

Print preview using javascript

Using javascript we can create printer friendly webpages.We can use window.print function to print a webpage.
The script is as follows.

<a href="javascript:window.print()">Click to Print This Page</a>

When we click on the print button a print dialog window will open and we can either print the page or can cancel the print. Using this method we cant find the preview of the print page. Using the following script we can generate a popup and the popup holds the data that has to be printed. So we can get print preview of the web page.

Step 1 : Create a div area that holds the print content.

example :

<div id="printsection">
<table width="652" border="0">
<tr>
<td width="30" height="24">&nbsp;</td>
<td width="606"><strong>This is a sample content for printing</strong></td>
</tr>
<tr>
<td height="129">&nbsp;</td>
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like.</td>
</tr>
</table>
</div>

here the div 'printsection' holds the print content.

Step 2 : Create a javascript function to open the popup

example :


<script language="javascript">
function printPage(printContent) {
var display_setting="toolbar=yes,menubar=yes,";
display_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
var printpage=window.open("","",display_setting);
printpage.document.open();
printpage.document.write('<html><head><title>Print Page</title></head>');
printpage.document.write('<body onLoad="self.print()" align="center">'+ printContent +'</body></html>');
printpage.document.close();
printpage.focus();
}
</script>

This function generates a window that contain the printing data.
Add the above code the <head> area. Here we can set the display settins like tool bar,menu bar , window height etc.

Step 3 : Call the function from the html page.

Call the above function from the html page.

example :

<a href="javascript:void(0);" onClick="printPage(printsection.innerHTML)">Print Preview</a>

That's all. It will popup a window and the print dialog box.

Full Source Code :

<html>
<head>
<title>Print Preview Sample</title>
<script language="javascript">
function printPage(printContent) {
var display_setting="toolbar=yes,menubar=yes,";
display_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";


var printpage=window.open("","",display_setting);
printpage.document.open();
printpage.document.write('<html><head><title>Print Page</title></head>');
printpage.document.write('<body onLoad="self.print()" align="center">'+ printContent +'</body></html>');
printpage.document.close();
printpage.focus();
}
</script>
</head>
<body>
<div id="printsection">
<table width="652" border="0">
<tr>
<td width="30" height="24">&nbsp;</td>
<td width="606"><strong>This is a sample content for printing</strong></td>
</tr>
<tr>
<td height="129">&nbsp;</td>
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like.</td>
</tr>
</table>

</div>
<a href="javascript:void(0);" onClick="printPage(printsection.innerHTML)">Print Preview</a>
</body>
</html>


Sunday, May 10, 2009

Remove textbox value when click on textbox

We saw many search textbox contains the word 'search' and when we click on the text box the text will remove. We are using javascript to do this.


The code is as follows

<input type="text" onblur="javascript:if (this.value == '') { this.value = 'Search'; }" onfocus="javascript:if (this.value == ''Search'') { this.value = ''; }" value="'Search'" id="txtsearch" name="txtsearch">

Thursday, May 7, 2009

Pagination using PHP-MySQL

Simple pagination using PHP-MySQL

Paging means showing your query result in multiple pages instead of just put them all in one long page. Imagine waiting for five minutes just to load a search page that shows 1000 result. By splitting the result in multiple pages you can save download time plus you don't have much scrolling to do.

To show the result of a query in several pages first you need to know how many rows you have and how many rows per page you want to show. For example if I have 95 rows and I show 10 rows per page that mean I'll have ten pages (rounded up).So the pagination needs several steps to complete.

Step 1: Create a Database connection

Establish a database cconnection to execute the select query.
<?
DEFINE ('DB_USER', 'dbusername');
DEFINE ('DB_PASSWORD', 'dbpassword');
DEFINE ('DB_HOST', 'dbroot');
DEFINE ('DB_NAME', 'dbname');

$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
?>

Step 2:

Find the total number of records and the current page number. If the current page number is not specified then it tooks as first page. After that we can calculate the total number of pages.This is calculated by total records / row per page. For the first time the page value will be null, so by default we will set the limit to 10 and page to 1.
<?
extract($_GET);
// number of rows in one page
$page_rows = 10;
// this will find the total number of records in the table
$data = mysql_query("SELECT count(id) as totcount FROM user") or die(mysql_error());
$row_num = mysql_fetch_object($data);
$rows = $row_num->totcount;
// this function will find how much page is neded for pagination.
$last = ceil($rows/$page_rows);
if ($pagenum < 1)
$pagenum = 1;
elseif ($pagenum > $last)
$pagenum = $last;
?>
If this variables are not blank, i.e. if the users click on the next or previous or page links then the page number and number of items to displayed will be not null and we will display data accordingly.

Step 3:Listing the datas


After that we can display the selected values.
<?
$counter = $starter+1;
while($info = mysql_fetch_array( $data_p ))
{
?>
<tr >
<td height="21">&nbsp;</td>
<td><?=$count++?></td>
<td><?=$info['username'];?></td>
<td><?=$info['email']?></td>
</tr>
<?php
}
?>

Step 4

: Set up the previous,next options.
<?php
if ($pagenum != 1)
{
$previous = $pagenum-1;
?>
<a href="?pagenum=1" onclick=""> <<-First</a>&nbsp;&nbsp;
<a href="?pagenum=<?=$previous?>"> <-Previous</a>
<?php
}
?></td>
<td width="296">
<?php
if ($pagenum != $last)
{
$next = $pagenum+1;
?>
<a href="?pagenum=<?=$next?>" >Next -></a>&nbsp;&nbsp;
<a href="?pagenum=<?=$last?>" >Last ->></a>
<?php
}
?>
This area tells the user which page is currently being viewed, the total number of pages available, and contains links to go either forwards or backwards through the available pages. The hyperlinks are displayed as simple text if there are no previous or next pages. Note that these hyperlinks do not put the word FIRST, PREV, NEXT or LAST as a parameter in the URL string - they all specify an absolute page number in the format pagenum =value

Source Code

This is the complete source code
<?php
// will extract the GET value "pagenum"
extract($_GET);
// number of rows in one page
$page_rows = 10;
// data base connectivity code starts
$con = mysql_connect('localhost','root','');
if(!$con)
{
echo "could not connect";
}
mysql_select_db('test');
// data base connectivity code ends
// this will find the total number of records in the table
$data = mysql_query("SELECT count(id) as totcount FROM user") or die(mysql_error());
$row_num = mysql_fetch_object($data);
$rows = $row_num->totcount;
// this function will find how much page is neded for pagination.
$last = ceil($rows/$page_rows);
if ($pagenum < 1)
$pagenum = 1;
elseif ($pagenum > $last)
$pagenum = $last;
// this code find, the starting record of the table for SQL selection
$starter = ($pagenum - 1) * $page_rows;
$count = $starter+1;
$max = 'limit ' .$starter.',' .$page_rows;
// executing the query
$data_p = mysql_query("SELECT id,username,email FROM user $max") or die(mysql_error());
?>
<form name="frmpagination" method="post">
<table width="609" height="107" border="0" class="boarder" cellpadding="0" cellspacing="0">
<tr>
<td height="21">&nbsp;</td>
<td>&nbsp;</td>
<td colspan="2"></td>
</tr>
<tr>
<td width="14" height="21">&nbsp;</td>
<td width="55"><strong>Sl No</strong></td>
<td width="261"><strong>Name</strong></td>
<td width="279"><strong>Mail Id</strong></td>
</tr>
<tr>
<td colspan="4"><hr /></td></tr>
<?php
$counter = $starter+1;
while($info = mysql_fetch_array( $data_p ))
{
?>
<tr >
<td height="21">&nbsp;</td>
<td><?=$count++?></td>
<td><?=$info['username'];?></td>
<td><?=$info['email']?></td>
</tr>
<?php
}
?>
<tr>
<td height="21">&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td height="21">&nbsp;</td>
<td>&nbsp;</td>
<td colspan="2"></td>
</tr>
<tr>
<td height="21">&nbsp;</td>
<td colspan="3"><table width="600" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="43">&nbsp;</td>
<td width="253">
<?php
if ($pagenum != 1)
{
$previous = $pagenum-1;
?>
<a href="?pagenum=1" onclick=""> <<-First</a>&nbsp;&nbsp;
<a href="?pagenum=<?=$previous?>"> <-Previous</a>
<?php
}
?></td>
<td width="296">
<?php
if ($pagenum != $last)
{
$next = $pagenum+1;
?>
<a href="?pagenum=<?=$next?>" >Next -></a>&nbsp;&nbsp;
<a href="?pagenum=<?=$last?>" >Last ->></a>
<?php
}
?> </td>
</tr>
</table></td>
</tr>
</table>
</form>