Saturday, December 12, 2009

How to parse XML data using PHP

Parse XML data using PHP

XML stands for eXtensible Markup Language and is used primarily for data storage and organization. It is useful for many things but the main thing about it is that there are no predefined tags.If we want to parse an XML data to use, we need to convert that data for PHP use. The following is an example for XML parsing using PHP

A few more rules about XML and we will be on our way to our PHP code. XML documents must be well-formed. This means that there can be only one root element (the top most element), all child elements must be nested properly <p>foo <b>bar</b></p> not <p>foo <b>bar</p></b>, and all elements must have end tags.In XML, an element is also referred to as a node

A sample xml code could look like this:

<?xml version="1.0"?>
<datas>
<sample 1 />
<sample 2 />
<sample 3 />

</datas>

<?xml version="1.0"?> must be the first tag in a XML file. It is called the xml declaration and identifies the file as a XML file to a parser.

As we can see the code is easy to read and understand. We can clearly see every tag and easily read them in plain English, or whatever language we are most comfortable with.Each XML file can have it's own DTD or structure. The PHP file using the XML parser must be tailored to one particular structure or DTD

Step 1:

The $xmlData is a variable contains the XML data.If the xml data is in the XML file then read the file and store that datas in a variable.We can use file operations to get the value from the XML file .
$xmlData ='<?xml version="1.0"?>
<sections>
<section name="profile">
<subsection name="name" value="Sample name"/>
<subsection name="address" value="sample address" />
<subsection name="email" value="sample@email.com" />
</section>
<section name="personel">
<subsection name="phone" value="123456789" />
<subsection name="age" value="25" />
<subsection name="job" value="Software Professional" />
</section>
</sections>';

Step 2:

After that we can parse the XML data. For this we can use the following code.The following code will parse the XML data and create a two dimensional array of data. This function parse each tag and stores each tag value in the array.

To view the array content

/*
This function receives xml data as input and returns an array as output.
*/
function xml2array($contents, $get_attributes=1)
{
if(!$contents) return array();

if(!function_exists('xml_parser_create')) {
return array();
}
//Get the XML parser of PHP - PHP must have this module for the parser to work
$parser = xml_parser_create();
xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $parser, $contents, $xml_values );
xml_parser_free( $parser );
if(!$xml_values) return;//Hmm...
//Initializations
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();
$current = &$xml_array;
//Go through the tags.
foreach($xml_values as $data) {
unset($attributes,$value);//Remove existing values, or there will be trouble
//This command will extract these variables into the foreach scope
// tag(string), type(string), level(int), attributes(array).
extract($data);//We could use the array by itself, but this cooler.
$result = '';
if($get_attributes) {//The second argument of the function decides this.
$result = array();
if(isset($value)) $result['value'] = $value;
//Set the attributes too.
if(isset($attributes)) {
foreach($attributes as $attr => $val) {
if($get_attributes == 1) $result['attr'][$attr] = $val;
//Set all the attributes in a array called 'attr'
/** :TODO: should we change the key name to '_attr'?
Someone may use the tagname 'attr'. Same goes for 'value' too */
}
}
} elseif(isset($value)) {
$result = $value;
}
//See tag status and do the needed.
if($type == "open") {//The starting of the tag ''
$parent[$level-1] = &$current;
if(!is_array($current) or (!in_array($tag, array_keys($current)))) {
//Insert New tag
$current[$tag] = $result;
$current = &$current[$tag];
} else { //There was another element with the same tag name
if(isset($current[$tag][0])) {
array_push($current[$tag], $result);
} else {
$current[$tag] = array($current[$tag],$result);
}
$last = count($current[$tag]) - 1;
$current = &$current[$tag][$last];
}
} elseif($type == "complete") { //Tags that ends in 1 line ''
//See if the key is already taken.
if(!isset($current[$tag])) { //New Key
$current[$tag] = $result;
} else { //If taken, put all things inside a list(array)
if((is_array($current[$tag]) and $get_attributes == 0)
//If it is already an array...
or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
array_push($current[$tag],$result); // ...push the new element into that array.
} else { //If it is not an array...
$current[$tag] = array($current[$tag],$result);
//...Make it an array using using the existing value and the new value
}
}
} elseif($type == 'close') { //End of tag '
'
$current = &$parent[$level-1];
}
}
return($xml_array);
}

Working:
The xml_parser_set_option() function sets options in an XML parser.This function returns TRUE on success, or FALSE on failure.
eg: xml_parser_set_option(parser,option,value) ;
This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.

There are three types of tags in the above example,sections,section and subsection. 'Sections' is the primary tag for the XML data. 'section' is the tag,with a reference name.'subsection' has the name and value parameters.The above function parse each tag and subtag and store the tag values in the array.

Step 3 :

After execuitng the above function, it returns all the wanted and unwanted datas.So we have to filter the datas. We are using the following the function to filter the datas.
$result = xml2array($xmlData, $get_attributes=1);
/*
The array '$result' contains all parsed datas. So we have to refined the datas
as our need. For that purpose we will iterate the '$result' array. We are using
seperate iteration for each section.
*/
$datalength = sizeof($result['sections']['section'][0]['subsection']);
$ary_profile = array();
for($x = 0;$x
The data from the XML data is now held in $result and can be accessed using a standard PHP loop.

The following is the output for the above function

Final Output
Array (
[0] => Sample name

[1] => sample address

[2] => sample@email.com

)
Array (
[0] => 123456789

[1] => 25

[2] => Software Professional

)

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>

Tuesday, April 21, 2009

How to store an array in a session?

Sometimes it's necessary to temporarily store data specific to a particular user while he/she surfs our website. For example, to make an admin control panel we have to check the admin session in every page.. PHP sessions provide you with just such a facility. We can store an array in a session variable. store multiple values with one reference we can use arrays, and can store these arrays in sessioon.
Sample code
<?php
session_start();
$_SESSION['admin']=array('adid'=>1,'adname'=>'main admin','privilage'=>'super','lastlogin'=>'12-May-2008');
?>
The above code will assign the array values to the session named 'admin'.
To view the array content
<?php
echo "<pre>";
print_r($_SESSION['admin']);
echo "</pre>";
// To get a particular element
echo "<pre>";
print_r($_SESSION['admin']['adname']);
echo "</pre>";
?>

To get all the values from the session array. This loop will list all elements in the session array.So we can use all these values using only one session.
<?php
foreach($_SESSION['admin'] as $key=>$value)
{
// it will print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

The output is :
The value of $_SESSION['adid'] is '1'
The value of $_SESSION['adname'] is 'main admin'
The value of $_SESSION['privilage'] is 'super'
The value of $_SESSION['lastlogin'] is '12-May-2008'

Sunday, January 25, 2009

Alternating table row colors

Here is a nice simple way of alternating table row colours.
The example is shown in PHP but the principal can be applied in any language.

Step 1 : First I create a very simple style for each row.
<style type=”text/css”>
.row1 { background: #000; color: #fff; }
.row0 { background: #fff; color: #000;}
</style>
Step 2 : Now I create a simple loop that prints my rows
<?php
print '<table>';
#Start at 0
$row = 0;
for ( $counter = 0; $counter <= 5; $counter ++)
{
$row = 1 - $row;
#Now I print the row with it’s css class name ‘row1' or 'row0′
print "<tr class=\"row$row\"><td>Row $row</td></tr>\n";
}
print '</table>';
?>

Source Code
<!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>Colour Change sample</title>
<style type="text/css">
.row1 { background: #000; color: #fff; }
.row0 { background: #fff; color: #000;}
</style>
</head>
<body>
<?php
print '<table>';
#Start at 0
$row = 0;
for ( $counter = 0; $counter <= 5; $counter ++)
{
$row = 1 - $row;
#Now I print the row with it’s css class name ‘row1' or 'row0′
print "<tr class=\"row$row\"><td>Row $row</td></tr>\n";
}
print '</table>';
?>
</body>
</html>