28 January 2011

Storage Area Networks PART 2 : Protocol and Devices

PROTOCOLS


FCIP: Entire Fibre Channel Frame Over IP
Fibre Channel Over TCP/IP (FCIP) describes mechanisms that allow the interconnection of islands of Fibre Channel storage area networks over IP-based networks to form a unified storage area network in a single Fibre Channel fabric. FCIP relies on IP-based network services to provide the connectivity between the storage area network islands over local area networks, metropolitan area networks, or wide area networks.

FCP: Fibre Channel Protocol
Fibre Channel Protocol (FCP) is the interface protocol of SCSI on the Fibre Channel.

iFCP: Internet Fibre Channel Protocol
Internet Fibre Channel Protocol (iFCP) is a gateway-to-gateway protocol, which provides fibre channel fabric services to fibre channel devices over a TCP/IP network. iFCP uses TCP to provide congestion control, error detection and recovery

iSCSI: Internet Small Computer System Interface
Internet Small Computer System Interface (iSCSI) is a TCP/IP-based protocol for establishing and managing connections between IP-based storage devices, hosts and clients, which is called Storage Area Network (SAN)

iSNS: Internet Storage Name Service
iSNS facilitates scalable configuration and management of iSCSI and Fibre Channel (FCP) storage devices in an IP network, by providing a set of services comparable to that available in Fibre Channel networks. iSNS thus allows a commodity IP network to function at a comparable level of intelligence to a Fibre Channel fabric. 

NDMP: Network Data Management Protocol
The Network Data Management Protocol (NDMP) is an open protocol for enterprise-wide network based data management. NDMP defines a network-based mechanism and protocol for controlling backup, recovery, and other transfers of data between primary and secondary storage.   

The NDMP (version 5) architecture is based on the client server model. The backup management software is considered the client, namely NDMP data management application (DMA)


SAS: Serial Attached SCSI
Serial Attached SCSI (SAS) is an evolutionary replacement for the Parallel SCSI physical storage interface. Serial Attached SCSI offers much faster communication and easier configuration. In addition, Serial Attached SCSI provides device compatibility to Serial ATA and uses similar cabling.

SCSI: Small Computer System Interface
Small Computer System Interface (SCSI), an ANSI standard, is a parallel interface standard used by Apple Macintosh computers, PCs, and many UNIX systems for attaching peripheral devices to computers. SCSI interfaces provide for faster data transmission rates than standard serial and parallel ports. In addition, you can attach many devices to a single SCSI port. There are many variations of SCSI: SCSI-1, SCSI-2, SCSI-3 and the recently approved standard Serial Attached SCSI (SAS).

Devices

Disk Array

A disk array is a disk storage system which contains multiple disk drives. It is differentiated from a disk enclosure, in that an array has cachememory and advanced functionality, like RAID and virtualization.
Components of a typical disk array include:
  • Disk array controllers
  • Cache memories
  • Disk enclosures
  • Power supplies

Typically a disk array provides increased availability, resiliency and maintainability by using additional, redundant components (controllers, power supplies, fans, etc.), often up to the point when all single points of failure (SPOFs) are eliminated from the design. Additionally those components are often hot-swappable.
Typically, disk arrays are divided into categories:
  • Network attached storage (NAS) arrays
  • storage area network (SAN) arrays:
  • Modular SAN arrays
  • Monolithic SAN arrays
  • Utility Storage Arrays
  • Storage virtualization



Tape Devices
A tape library, sometimes called a tape silo, tape robot or tape jukebox, is a storage device which contains one or more tape drives, a number of slots to hold tape cartridges, a barcode reader to identify tape cartridges and an automated method for loading tapes (a robot).

Optical JukeBox

An optical jukebox is a robotic data storage device that can automatically load and unload optical discs, such as Compact Disc, DVD, Ultra Density Optical or Blu-ray disc and can provide terabytes and petabytes of tertiary storage. The devices are often called optical disk libraries, robotic drives, or autochangers. Jukebox devices may have up to 2,000 slots for disks, and usually have a picking device that traverses the slots and drives. The arrangement of the slots and picking devices affects performance, depending on the space between a disk and the picking device. Seek times and transfer rates vary depending upon the optical technology.
Jukeboxes typically contain internal SCSI or SATA based recordable drives (CD-ROM, CD-R, DVD-ROM, DVD-R, DVD-RAM, UDO or Blu-ray) that connect directly to a file server and are managed by a third party jukebox management software. This software controls the movement of media within the jukebox, and the pre-mastering of data prior to the recording process



List of SAN network management systems

  • Apple Xsan
  • Brocade Fabric Manager
  • Cisco Fabric Manager
  • Dataram XcelaSAN
  • Enterprise Fabric Connectivity (EFC) Manager
  • euroNAS (iSCSI and NAS Software)
  • EMC VisualSAN
  • EMC VisualSRM
  • EMC ControlCenter
  • EMC Invista
  • Open-E DSS V6 (Data Storage Software)
  • FalconStor IPstor family
  • StarWind StarWind iSCSI SAN
  • DataCore SANmelody and SANsymphony
  • Hitachi Data Systems HiCommand
  • HP OpenView Storage Area Manager
  • IBM SAN Volume Controller
  • Symantec Veritas Command central Storage
references:
http://en.wikipedia.org
http://www.javvin.com
http://www.skills2earn.com


Some Useful JavaScript Snippets


1. Close Window
< form>
< input onclick="javascript:window.close();" type="button" value="Close Window" />< /form>


2. Add to Favorites
< a href="javascript:window.external.AddFavorite('http://www.skills2earn.com', 'skills2earn')">Add to Favorites< /a>

3. To prevent your page being framed by someone else put this event handler into the body tag.
< body onLoad="if (self != top) top.location = self.location">

4. Pop up window
< HTML>
< HEAD>
< TITLE> A Window< /TITLE>
< SCRIPT>

function open_window(url) {
mywin = window.open(url,"win",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=520,height=350');
}

< /SCRIPT>
< /HEAD>

< BODY>

< A HREF = "javascript:open_window('page1.html')">
< IMG SRC ="image.gif">
< /A>

< A HREF = "javascript:open_window('page2.html')">
< IMG SRC ="image.gif">
< /A>

< /BODY>
< /HTML>

5. Determine if Browser Understands HTML5 Video
// Check if the browser understands the video element.
function understands_video() {
return !!document.createElement('video').canPlayType; // boolean
}

if ( !understands_video() ) {
// Must be older browser or IE.
// Maybe do something like hide custom
// HTML5 controls. Or whatever...
videoControls.style.display = 'none';
}

6. Delayed Redirect
setTimeout( "window.location.href =
'http://walkerwines.com.au/'", 5*1000 );

7. Email Validation
< script language="JavaScript1.2">
var testresults
function checkemail(){
var str=document.validation.emailcheck.value
var filter=/^.+@.+\..{2,3}$/

if (filter.test(str))
testresults=true
else {
alert("Please input a valid email address!")
testresults=false
}
return (testresults)
}
< /script>
< script>
function checkbae(){
if (document.layers||document.all)
return checkemail()
else
return true
}
< /script>

8. Select All
< script language="Javascript">

function selectAll(theField) {
  var tempval=eval("document."+theField)
  tempval.focus()
  tempval.select()
}

< /script>

Enable Cross Database Ownership Chaining


Use DataBaseName
go
Alter Database DataBaseName
SET DB_chaining ON
go
EXEC sp_grantdbaccess 'GUEST'
go
Grant CONNECT to GUEST
go
Grant SELECT to Guest
go

25 January 2011

Php Array Pagination Script

Sometimes we are trapped in a situation where we have thousands of elements in an array variable and we can not just show this much data on the page. So for such situations I am sharing a very easy simple to integrate php array pagination script. By using this script one can easily paginate an array variable with thousands of elements.

Complete paging script is mentioned below:
<?php
///////////////FILLING ARRAY WITH DUMMY DATA////////////////////
$key = array();
for($i=0; $i<200; $i++)
{
 //fill array data
 $key[] = "num = ".$i;
}
////////////////////////////////////////////////////////////////

/////////////////////START OF ARRAY PAGINATION CODE/////////////////////
$ptemp="http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$pt=explode('&',$ptemp);
if (strpos($ptemp,'pageno'))
 array_pop($pt);
$pt=implode('&',$pt);
$ptemp=$pt;
$array=$key; // REPLACE $KEY WITH YOUR ARRAY VARIABLE
$page = $_REQUEST['pageno'];

$currentpage = isset($page) ? (integer)$page : 1;
$numperpage = 10; //NUMBER OF RECORDS TO BE DISPLAYED PER PAGE

$total = count($array);
$numofpages = ceil($total / $numperpage); //TOTAL NUMBER OF PAGES

if(isset($array))
{
    if (($currentpage > 0) && ($currentpages <= $numofpages))
 {
        //STARTING LOOP FOR ARRAY DATA
        $start = ($currentpage-1) * $numperpage;
        for($i=$start;$i<=($numperpage+$start-1);$i++) 
  {
            ///////////PLACE YOUR CODE HERE//////////////////////////
            echo $array[$i] .'<br />';
   ////////////////////////////////////////////////////////
        }
 }
}
if ($currentpage != 1) 
{ //GOING BACK FROM PAGE 1 SHOULD NOT BET ALLOWED
 $previous_page = $currentpage - 1;
 $previous = '<a href="'.$ptemp.'?pageno='.$previous_page.'"> <</a> ';    
}    
$pages = '';
for ($a=1; $a<=$numofpages; $a++)
{
  if ($a == $currentpage) 
 $pages .= $a .'</u> ';
  else 
 $pages .= '<a href="'.$ptemp.'?pageno='.$a.'" >'. $a .'</a> ';
}
$pages = substr($pages,0,-1); //REMOVING THE LAST COMMA (,)

if ($currentpage != $numofpages) 
{ //GOING AHEAD OF LAST PAGE SHOULD NOT BE ALLOWED
 $next_page = $currentpage + 1;
 $next = ' <a href="'.$ptemp.'?pageno='.$next_page.'"> ></a>';
}
echo '<br /><br />'. $previous . $pages . $next; //PAGINATION LINKS
/////////////////////END OF ARRAY PAGINATION CODE/////////////////////
?>
For any queries or problems that you may have while integrating this script, feel free to ask by commenting on this post.

Related Post: Mysql Php Pagination Script

20 January 2011

Storage Area Networks PART 1

Storage Area Network (SAN) is a high-speed subnetwork of shared storage devices. A storage device is a machine that contains nothing but a disk or disks for storing data. A typical SAN consists of a farm of disk arrays, CD-ROM, tape libraries, etc. interconnected with Fiber channel and connected to the outside world through a Fiber channel switch or bridge. The connections inside the boxes can be Fibre channel, SCSI, ATA  or any other technology. Connecting all the storage devices into a network needs a plethora of hubs, bridges, routers, multiplexers, copper to optical converters, and other relevant devices as we do for a normal communications network

SANs originated to overcome the problems with network attached storage (NAS) devices, which - like ordinary servers - are difficult to manage and difficult to expand the capacity on. NAS devices also add to the traffic on the network and suffer from the delays introduced by the operating systems' network stacks. A SAN's architecture works in a way that makes all storage devices available to all servers on a LAN or WAN. As more storage devices are added to a SAN, they too will be accessible from any server in the larger network. In this case, the server merely acts as a pathway between the end user and the stored data.

A SAN is made up of a number of fabric switches connected in a network. The most common form of SAN uses the Fibre Channel fabric protocol (with Fibre Channel switches). Alternatively ISCSI could be used with IP switches. Connected to the SAN will be one or more Disk array controllers and one or more servers. The SAN allows the storage space on the hard disks in the Disk array controllers to be shared amongst the servers.

Few SAN Solution Providers

  • McDATA - providing SAN solutions.
  • Storage Area Network (SAN) Test Solutions
  • SAN software and hardware solutions
  • SAN Appliances provider
  • Storage Area Network Appliance from Stonefly
  • SAN Solutions by Rorke
  • SAN Solutions by Dot Hill
  • SAN Consulting Services
  • SAN solutions for data intensive, enterprise applications.
  • Tivoli Storage Area Networks (SAN) Solutions
  • SOFTEK - Storage Management Software - Storage Area Network (SAN) Solutions
  • Brocade develops Storage Area Network (SAN) infrastructure solutions that simplify the deployment and management of SANs
  • SAN Solutions from Sun
  • Simple, Safe, and Scalable SAN management solution
  • HCL Technologies - Storage Area Networks (SAN) - Solutions and Services
  • SAN Solutions by Legato
  • AT&T
  • HP Storage Works
  • DELL EMC
SAN Advantages
  1. SAN Architecture facilitates scalability - Any number of storage devices can be added to store hundreds of terabytes
  2. SAN reduces down time - We can upgrade our SAN, replace defective drives, backup our data without taking any servers offline. A well-configured SAN with mirroring and redundant servers can bring zero downtime.
  3. Sharing SAN is possible - As SAN is not directly attached with any particular server or network, a SAN can be shared by all
  4. SAN provides long distance connectivity - With Fibre channel capable of running upto 10 kilometers, we can keep our data in a remote, physically secure location.  Fibre channel switching also makes it very easy to establish private connections with other SANs for mirroring, backup, or maintenance.
  5. SAN is truly versatile - A SAN can be single entity, a master grouping of several SANs and can include SANs in remote locations.
SAN Disadvantages
  1. SANs are very expensive as Fibre channel technology tends to be pricier and maintenance requires a higher degree of skill
  2. Leveraging of existing technology investments tends to be much difficult. Though SAN facilitates to make use of already existing legacy storage, lack of SAN-building skills has greatly diminished deployment of homegrown SANs. So currently pre-packaged SANs based on Fibre channel technology are being used among the enterprises.
  3. Management of SAN systems has proved to be a real tough one due to various reasons. Also for some, having a SAN storage facility seems to be wasteful one.
  4. Also, there are a few SAN product vendors due to its very high price and very few mega enterprises need SAN set up.

Some Storage Technologies
  • Content Addressed Storage (CAS)
  • Fibre Channel
  • Teradata
  • Hierarchical Storage Management (HSM)
  • Internet Small Computer Systems Interface (iSCSI)
  • IP-based Storage
  • Network Attached Storage (NAS)
  • Optical Storage Technology
  • Storage Area Network (SAN) 
  • Redundant Array of Inexpensive Disks (RAID)


18 January 2011

How to enable slow query logs in mysql

Many a times it happens that our web server gets too busy and ultimately goes unresponsive. And we dont even know why it happened. For such situations I recommend you should enable slow query logging in mysql and try to optimize your slow queries.

Slow query logging can be easily enabled by following the below mentioned steps:

Step 1:
You need to edit the file "/etc/my.cnf" and place the following code in it.
log-slow-queries=/var/lib/mysql/slow.log
long_query_time = 6
Note: Dont forget to take the backup of "my.cnf".

The first line will enable the slow query logging and specifies the path where the log is to be saved. The second line will set the criteria for slow queries. That is queries that takes more then 6 seconds will be considered as slow queries.


Step 2:
Now after updating "my.cnf" you need to restart mysql. This can be done using any of the below mentioned shell commands.
service mysqld restart
OR
/etc/init.d/mysqld restart
Step 3:
After restarting you need to flush mysql logs in order to get the file automatically created. This can be done by using the below mentioned shell command:
mysqladmin flush-logs
Well guys i guess thats it, you have successfully enabled slow query logging in mysql. For any queries that you may have, feel free to comment.

16 January 2011

SQL Server Profiler Identifying Deprecated Features

Sql Server 2005 has events in profiler that can be captured to identify the code with deprecated features.

Following steps are required inorder to have the required information logged in through profiler.
  • Navigate to Start >All Programs >Microsoft SQL Server 2005 >Performance Tools >SQL Server Profiler. OR
  • Navigate to StartMenu>Run>(type) profiler90
  • Start a New Trace after authenticating to Sql server that you wish to profile.
  • In trace properties at general tab select save information in file or table.
  • In order to review all events, enable the check box for 'Show all events' and 'Show all columns' on the bottom right of the screen
  • Then navigate to the 'Deprecation' heading and enable the 'Deprecation Announcement' and 'Deprecation Final Support' events
  • Press RUN
  • Analyze the results which says 'Deprecation Announcement'.

14 January 2011

Installing and configuring SharePoint 2010 with Web application and Site Collection

List of Prerequisites Software
  1. Windows server 2008 with SP 2 / Windows 7 / Vista
  2. Windows 2008 R2 and Windows Server 2008 KB971831
  3. WCF Fix article for Windows 2008 R2 and Windows 7 KB976462
  4. Microsoft SQL Server 2008 Native Client
  5. Microsoft "Geneva" Framework Runtime
  6. Microsoft Sync Framework Runtime v1.0 (x64)
  7. Microsoft Chart Controls for Microsoft .NET Framework 3.5
  8. Microsoft SQL Server 2008 Analysis Services ADOMD.NET
  9. SQL Server 2008 SP1
  10. .NET Framework 3.5 Service Pack 1 (Full Package) KB959209 KB967190


Create our top level web application 

13 January 2011

Php For Beginners (Lesson 8)

In this lesson we will discuss functions in php. A function is a block of code which is declared once on a page and then used each time it is needed in the script. For example if you are using some piece of code repetitively in your script then you can declare a function and place that code in the function. Now each time you need to use that code you don’t need to write the whole code again, instead you just call the function and your code will be called automatically.

There are two types of functions:

· Built-in Functions

· User Defined functions

Built-in Functions
Built-in Functions are those functions which are stored by default in php. Php has 700 built-in functions.

Example

  • strtolower(); Converts string to lowercase
  • strtoupper(); Converts string to upper case
  • exit(); Stops the execution of script

User Defined Functions
User defined functions are thoses functions which are declared by users for their own use.

Creating a function in php

A function should always be declared before it is going to be called.

Syntax

Function func_name (parameter1,parameter2,…..,parametern)

{ code to be executed. }

Example 1 (Function without parameters)

In this example we will create a function that takes no parameters and returns no value. This function will only prints our name on the screen.
<?php 
function display_name () 
{ 
   echo "Bill"; 
} 
echo "Hi there! My name is "; 
display_name(); 
?> 
The output of the above example will be “Hi there! My name is Bill”.

Example 2 (Function with parameters)

In this example we will create a function with a parameter. This function will take name as parameter when it is called an then display that name on the screen.
<?php 
function display_name ($name) 
{ 
   echo $name; 
} 
echo "Hi there! My name is "; 
display_name('Bill'); 
echo " and my brother's name is "; 
display_name('Jack'); 
?> 
The output of the above example will be “Hi there! My name is Bill and my brother's name is Jack”.

Example 3 (Function which returns value)

In this example we will create a function which returns some value. This function will take two numbers as parameter and returns the average.
<?php 
function average($num1,$num2) 
{ 
   $result=($num1 + $num2)/2; 
   return $result; 
} 
echo "The Average of 20 & 100 is ".average('20','100'); 
?> 
The output of this example will be “The Average of 20 & 100 is 60”.

Ok guys this is all about the functions in php. For any queries feel free to comment.


next Previous Lesson --- Next Lesson next

12 January 2011

SQL Server 2005 transaction locks

Utilizing the Dynamic Management Views is the best and easier way to do it ...
SELECT L.request_session_id AS SPID,
   DB_NAME(L.resource_database_id) AS DatabaseName, 
   O.Name AS LockedObjectName, 
   P.object_id AS LockedObjectId, 
   L.resource_type AS LockedResource, 
   L.request_mode AS LockType, 
   ST.text AS SqlStatementText, 
   ES.login_name AS LoginName, 
   ES.host_name AS HostName, 
   TST.is_user_transaction as IsUserTransaction, 
   AT.name as TransactionName, 
   CN.auth_scheme as AuthenticationMethod 
FROM sys.dm_tran_locks L 
   JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id 
   JOIN sys.objects O ON O.object_id = P.object_id 
   JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id 
   JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id 
   JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id 
   JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id 
   CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST 
WHERE resource_database_id = db_id() 
   ORDER BY L.request_session_id 

sys.dm_tran_locks:
Shows us all locks held on all resources for all transaction. We start from this view since we want to get information about locked resources.
sys.partitions:
Contains information about partitions in the database. We can join it to the sys.dm_tran_locks on the hobt_id only for resource_type values 'HOBT', 'Page', 'RID'  and 'Key'. With this join we get the object_id of our locked table.
sys.objects:
Contains data for all schema scoped database objects. We join it to sys.partitions to get the Name of the locked object which is usually a table name.
sys.dm_exec_sessions:
Shows data about all active sessions on SQL server. We join it to sys.dm_tran_locks to get user login information for each held lock.
sys.dm_tran_session_transactions:
Shows data for all transactions for a session. By joining in to sys.dm_exec_sessions we get a link to all active transactions in the session.
sys.dm_tran_active_transactions:
Shows data for all active transactions in SQL Server. By joining it to sys.dm_tran_session_transactions we only get information for the session we want.
sys.dm_exec_connections:
Shows data for all connections in SQL Server. By joining it to sys.dm_exec_sessions we get connection info for our session.
sys.dm_exec_sql_text:
Returns SQL statement that is associated with the SQL handle input parameter. By cross applying it to the sys.dm_exec_connections we get the last executed statement for the connection, which in our case is the statement that is holding locks.

Step by Step setting Transactional Replication in SQL Server 2008 R2

There are 3 steps involved for Configuring the Transactional Replication:

1.Configuring the Distribution Database.
A database which contains all the Replication commands. Whenever any DML or DDL schema changes are performed on the publisher, the corresponding commands generated by  SQL Server are stored in the Distribution database. This database can reside on the same server as the publisher, but it is always recommended to keep it on a separate server for better performance. Normally, I have observed that if you keep the distributoion database on the same machine as that of the publisher database and if there are many publishers then it always has an impact on the performance of the system. This is because for each publisher, one distrib.exe file gets created. 
2.Creating the publisher.
The Publisher can be referred to as a database on which the DML or DDL schema changes are going to be performed.
3.Creating the subscriber.
The Subscribers the database which is going to receive the DML as well as DDL schema changes which are performed on the publisher. The subscriber database normally resides on a different server in another location.

How it works

Transactional replication is implemented by the Snapshot Agent, Log Reader Agent, and Distribution Agent. The Snapshot Agent prepares snapshot files containing schema and data of published tables and database objects, stores the files in the snapshot folder, and records synchronization jobs in the distribution database on the Distributor.
The Log Reader Agent monitors the transaction log of each database configured for transactional replication and copies the transactions marked for replication from the transaction log into the distribution database. The Distribution Agent moves the initial snapshot jobs and the transactions held in the distribution database tables to Subscribers.


Configuring the Distribution Database










Allow a non admin user to restart a service in windows server 2008

  1. Obtain the user's SID (using a short script)
  2. Format the SDDL correctly
  3. Apply the permissions
  4. Verify the process
Script in VB for SID: (copy past script in notepad and save it as "SID.vbs" and run it)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objAccount = objWMIService.Get _
    ("Win32_UserAccount.Name='USERNAME',Domain='DomainName'")
Wscript.Echo objAccount.SID

Command for obtaining:
Security Descriptor Definition Language (SDDL)
cmd>> 
sc sdshow servicename (the name should be exact service name)

Command to grant permission:
cmd>>
sc sdset servicename D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)
(A;;CCLCSWLOCRRC;;;SU)(A;;RPWP;;;S-1-5-21-671767478-4120628812-988426340-2271)
Access granted!! your done, Please verify by starting the service with non admin user.

Description:
(A;;RPWP;;;S-1-5-21-671767478-4120628812-988426340-2271) 
replace SID with what u get from the above vb script
SID   -USERNAME
A      -Allow
RP    -Read all properties
WP   -Service handling


11 January 2011

Php For Beginners (Lesson 7)

In this lesson we will discuss loops in php. Loops are used to run a piece of code for a certain number of times. Php supports four types of loops:

  1. While Loop
  2. Do-While Loop
  3. For Loop
  4. Foreach Loop

While Loop

Syntax

While (condition)
{ code to be executed. }

Example
<?php 
$count=0; 
while ($count!=10) 
{ 
      echo $count."\n"; 
      $count++; 
} 
?>
The output of the above example will be counting from 0 to 9.

Do-While Loop

Syntax

Do
{ Code to be executed. }
While (condition)

Example
<?php 
$count=0; 
do 
{ 
      echo $count."\n"; 
      $count++; 
} 
while ($count!=10) 
?>
The output of the above example will be counting from 0 to 9.

For Loop

Syntax

for (initialize; condition; increment)
{ code to be executed. }

Example
<?php 
for ($i=0; $i<=10; $i++) 
{ 
      echo $count."\n"; 
} 
?>
The output of the above example will be counting from 0 to 10.

Foreach Loop

Syntax

foreach ($array as $value)
{ code to be executed. }

Example
<?php 
$count=array(0,1,2,3,4,5,6,7,8,9); 
foreach ($count as $value) 
{ 
   echo $value . "\n"; 
} 
?>
The output of the above example will be counting from 0 to 9.

References

http://www.php.net
http://www.w3schools.com

Ok guyz this is all for loops in php, keep practicing and for any queries don’t hesitate to comment and ask.


next Previous Lesson --- Next Lesson next

10 January 2011

Php For Beginners (Lesson 6)

In this lesson we will be discussing array variables, array variables are just like ordinary variables except that an array variable can store multiple values in one single variable.

For example if you want to store names of 5 students then you need to have 5 variables. What if students total exceeds 500? Then you will need 500+ variables to store those names. In such situations we will use a single array variable to store the names of all the students.

Array variables have indexes associated with each value, so that the values can be easily accessed using their respective indexes. These indexes can be numeric as well as strings.

Numeric Index Array

Example
<?php 
$student_name[0]=”Bill”; 
$student_name[1]=”Max”; 
$student_name[2]=”John”; 
$student_name[3]=”Smith”; 
echo $student_name[0].” And ”.$student_name[3].” Are good students”; 
?>
The output of above example will be “Bill and Smith Are good students”.

String Index Array

Example
<?php 
$marks[‘bill’]=”96”; 
$marks[‘max’]=”32”; 
$marks[‘john’]=”54”; 
$marks[‘smith’]=”78”; 
echo “Bill secured ”.$marks[‘bill’].” marks”; 
?>
The output of above example will be “Bill secured 96 marks”.

Multidimensional Array

In multidimensional array each element of the main array can also be an array and each element in that array may be an array too, and so on.

Example
<?php 
$students=Array
(
[‘Bill’] => Array
(
[0] => 78
[1] => 86
[2] => 92
)
[‘Max’] => Array
(
[0] => 45
)
[‘John’] => Array
(
[0] => 76
[1] => 63
[2] => 78
)
); 
echo “Bill secured ”.$students[‘Bill’][2].” marks”; 
?>
The output of the above example will be “Bill secured 92 marks”.

References

http://www.php.net
http://www.w3schools.com

I guess we have discussed all the fundamental concepts of array variables, in case of any queries please feel free to comment on this post.


next Previous Lesson --- Next Lesson next

09 January 2011

Php For Beginners (Lesson 5)

In this lesson we will be discussing conditional statements. Conditional statements are used when you want to relate an action with some condition. Php supports four types of conditional statements:

If Statement

Syntax

if (condition)
{ code to be executed }

Example
<?php
$a=5;
if ($a==5)
{
   echo “five”; // outputs “five”
} 
?>
If – else Statement

Syntax

if (condition)
{ code to be executed }
else { code to be executed }

Example
<?php
$a=5;
if ($a==5)
{
   echo “five”; // outputs “five”
}else
{ 
   echo “not five”;
}
?>
If – elseif – else Statement

Syntax

if (condition)
{ code to be executed }
elseif (condition)
   { code to be executed }
else { code to be executed }

Example
<?php
$a=2;
if ($a==5)
{
   echo “five”; 
}elseif ($a==6)
{
   echo “six”; 
}
else 
{ 
   echo “neither five nor six”;  // outputs “neither five nor six”
}
?>
Switch Statement

Syntax

switch (variable)
{
case test1:
  code to be executed if variable =test1;
  break;
case test2:
  code to be executed if variable =test2;
  break;
default:
  code to be executed if n is different from both test1 and test2;


Example
<?php
$a=2;
switch ($a)
{
case 5:
  echo “five”;
  break;
case 2:
  echo “two”; // outputs “two”
  break;
default:
  echo “neither five nor two”;
}  
?>
The switch statement takes variable as an argument and then code to be executed for each case. Whichever condition will be true it will execute its code and if no condition is true then it will execute the default code.

References

http://www.php.net
http://www.w3schools.com

This is all for the fifth lesson, now all you need to do is practice these concepts and if you have any queries then feel free to comment on this post.


next Previous Lesson --- Next Lesson next

08 January 2011

Php For Beginners (Lesson 4d)

If you are reading this lesson then I assume that you have read all of my previous lessons, so coming directly to the point, I will be discussing logical operators and their usage in php.

And Operator (&&)
"&&" operator is used to take the union of two or more conditions and returns true if and only if all the conditions are true.
<?php
$a=5;
$b=6;
if ($a==5 && $b==6)
    echo "true"; //Outputs true
?>
Or Operator (||)
"||" operator returns true if any of the condition is true.
<?php
$a=5;
$b=6;
if ($a==5 || $b==5)
   echo "true"; //Outputs true 
?>
Not Operator (!)
"!" operator returns true when no condition is true.
<?php
$a=5;
$b=6;
if !($a==$b)
   echo "true"; //Outputs true
?> 
Well that is all we need to know about Operators in php, keep reading and feel free to ask questions through comments.


next Previous Lesson --- Next Lesson next

07 January 2011

Php For Beginners (Lesson 4c)

In this lesson i will be discussing comparison operators and their applications in php.

== Operator

"==" operator is used for comparing two values or variables and return true if they are same.
<?php
$a=5;
if ($a==5)
   echo "Five";  //Outputs Five
?>
!= and <> Operator

"!=" and "<>" operators are also used for comparing two values or variables but they return true if the values are not same.
<?php
$a=5;
if ($a!=4)
   echo "Four";  //Outputs Four
if ($a<>4)
   echo "Four";  //Outputs Four
?>
> Operator

">" operator is used to check whether the first value is greater than second or not.
<?php
$a=5;
if ($a>4)
   echo "Greater";  //Outputs Greater 
?>
< Operator

"<" operator is used to check whether the first value is less than second or not.
<?php
$a=5;
if ($a<6)
   echo "Lesser";  //Outputs Lesser 
?>
>= Operator

">=" operator is used to check whether the first value is greater than or equal to the second value or not.
<?php
$a=5;
if ($a>=5)
   echo "Greater";  //Outputs Greater 
if ($a>=4)
   echo "Greater";  //Outputs Greater 
?>
<= Operator

"<=" operator is used to check whether the first value is less than or equal to the second value or not.
<?php
$a=5;
if ($a<=5)
   echo "Lesser";  //Outputs Lesser 
if ($a<=6)
   echo "Lesser";  //Outputs Lesser 
?>

Ok Guyz, that is all for this lesson, feel free to comment and ask any quries that you may have.


next Previous Lesson --- Next Lesson next