Sunday, 13 November 2011

PHP with Mysql

Retweet this button on every post blogger
Mysql is the world's most popular open source database System ,with its superior speed, reliability, and ease of use, MySQL has become the preferred choice for Web, Web 2.0 today's millions  database based applications runs on mysql for their data storage needs, learning mysql is relatively easy and has a several advantage over other paid RDBMS software's.


PHP provide a large base of its function repository for handling mysql operation efficiently. these functions allow you to access MySQL database servers.

The structure of PHP and Mysql connectivity.
 
 As you can determine from the above diagram there is three boxes


  1. One is a client is running  a web Browser and making request to web server.
  2. Second is a Web server that handle clients request and make Appropriate request to Web Database software running at the extreme end of the structure it stores all the data. 
you can learn more about Mysql and can see its documentation at Mysql Reference .

If you have installed WAMP or XAMPP Bundle on your Ssystem Mysql comes with that automatically.

Five Important commands of MySQL.
  1. mysql_connect("host_name","User","Password") 
        this PHP function open's a MySQL Connection With the three parameters  passed  called.         host_name : - The name of host on which your server is running .
        user_name :- user name of the Database.
         password: - password of the database.

     2. mysql_select _db("db_name",resource link);
         Select the database with the provide resource returned by the mysql_connect() call, by                          default connect with the last opened coonection.
   
    3. mysql_query("Query",resource link)
        sends a unique query (multiple queries are not supported) to the currently active database on the     server      that's associated with the specified link_identifier.
   
    4. mysql_fetch_array(resource $result, $result_type)
        Fetch a result row as an associative array, a numeric array, or both
    5.  mysql_num_rows( resource $result )
         Get number of rows in result.retrieves the number of rows from a result set. This command is only         valid for statements like SELECT or SHOW that return an actual result set.



Saturday, 25 June 2011

Lesson 15 : PHP Query String.

Retweet this button on every post blogger
Query string is usual part of any website it sits in the URL bar and associated with  website URL for navigation to the different sections of the website. use of query string to send data of one page to others.
Example of query string;
index.php?page=user&role=admin


The query string always starts with Question mark (?) and separates two variables with address operator(&).

Example program  of Query string  :-
page page1.php
<?php
if ( isset ( $_POST['submit'] ) )
{
     $url = "nextpage.php?fname=".$_POST['fname']."&lname=".$_POST['lname']."&fdigit=".$_POST['fdigit']."&sdigit=".$_POST['sdigit'];
header("Location:$url");
}


?>


<html>
<head><title>PHP Query String.</title></head>
<body>
<center>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table cellpadding="0" cellspacing="0">
<tr><td>Firt name</td><td><input type="text" name="fname" /></td></tr>
<tr><td>Last name</td><td><input type="text" name="lname" /></td></tr>
<tr><td>First digit</td><td><input type="text" name="fdigit" /></td></tr>
<tr><td>Second digit</td><td><input type="text" name="sdigit" /></td></tr>
<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="Go.." /></td></tr>
</table>
</form>
</center>
</body>
</html>


This program contains nothing the whole magic at the nextpage.php  


Page nextpage.php


<html>
<head><title>Next page</title></head>
<body>
<center>
<table cellpadding="0" cellspacing="0">
<tr><td>Firt name</td><td><?php echo $_GET['fname'];?></tr>
<tr><td>Last name</td><td><?php echo $_GET['lname'];?></td></tr>
<tr><td>First digit</td><td><?php echo $_GET['fdigit'];?></td></tr>
<tr><td>Last digit</td><td><?php echo $_GET['sdigit'];?></td></tr>
<?php

$sum  = $_GET['fdigit']+$_GET['sdigit'];
?>
<tr><td>Sum:</td><td><?php if ( isset ( $sum ) ) echo $sum; ?></td></tr>

</table>
</center>

</body>
</html>
There are two option to get value from a query string $_GET and $_REQUEST these both are PHP globals array.
The major drawback with Query string  that they can be manipulate while running.
TIP :- NEVER SEND SENSITIVE DATA USING QUERY STRING BECAUSE ITS SHOWS WHAT IS CONTAINS.   

Wednesday, 22 June 2011

Lesson 14 : PHP Script for Login & Louout.

Retweet this button on every post blogger
Login-Logout is a very basic mechanism for authenticate a user   User of your website or application. this mechanism always implemented using PHP session  variable.

$_SESSION is an associative array containing session variables available to the current script.
for registering a session variable we must have to start_session.
About session_start():-

Syntax : -

bool session_start ( void )

Returns TRUE if a session successfully started otherwise FALSE.
1. session_start — Initialize session data.
2. session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
3When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

PHP script for login logout :-

Example page index.php 

<?php
session_start();
if(isset($_POST['submit']))
{
$_SESSION['user'] = "user";
}
?>
<!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>log in page.</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!="")
{
header("Location: login.php");
}
?>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<center>
<div>
<fieldset style="width:300px;">
<legend>Login</legend>
<label id="userid"><input type="text" id="userid" name="userid"  /></label>
<label id="passwd"><input type="text" id="passwd" name="passwd"  /></label>
<input type="submit" name="submit" value="go" />
</fieldset>
</div>
</center>
</form>
</body>
</html>

Example page login.php

<?php
session_start();
if(!isset($_SESSION['user']))
header("Location: index.php");
else
echo "Congratulation you are logged in!!";
?>
<a href="logout.php" >Logout</a>

Example page logout.php

<?php
session_start();
unset($_SESSION['user']);
header("Location: index.php");
exit;
?>

Tuesday, 21 June 2011

Lesson 13 : PHP state management and Login Logout.

Retweet this button on every post blogger
Just because HTTP is a stateless protocol it does not remember what user has done last time or a last minute   we have to manually manage our state while communicating with the server, state management is a good topic  and it includes some core PHP basics such as Session state management , Query string, cookies and Databases.

Managing states in PHP :
.
PHP Cookies :-
Cookies are small piece of information that stored at the client side for later reference .
Some basic function of cookies are storing user name and a encrypted password at the client side when a user
click on the remember me check box, or when a website wants to track their user,.

PHP syntax for cookies are :

(PHP 4, PHP 5)
setcookie — Send a cookie
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [,bool $secure = false [, bool $httponly = false ]]]]]] )


Tips :-
1. A cookie  must be set before ant output is sent to the browser, this is the same condition as for header including <html><head> tag and ant whitespace. 

An example of using cookies :
<?php
//this file is included
if(isset($_POST['set']))
{
    if ( setcookie("name","developer",time()+30) ) //thirty seconds expiry time
    echo "Cookie has been set successfully!";
    else
   echo "FAIL";
}
?>
<html>
<head><title>PHP cookies.</title></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> method="post" >
<table>
<tr><td>Name</td><input type="text" name="name" /></tr>
<tr><td>&nbsp;</td><input type="submit" name="set" value="setcookie" /></tr>
</table>
</form>
</body>
</html


save this as name anyname.php


Now retrieving value from a cookie : -
Once the cookie has been set it have to retrieved on the next page for that purpose we use $_COOKIE superglobal array it is  An associative array of variables passed to the current script via HTTP Cookies. 
An example for $_COOKIE :- 
<?php
     echo "Getting value the saved cookie";
    $value = $_COOKIE['name'];
   echo "<br/>";
  echo  "Cookie value is : " .$value;
?>


save this page to anyname.php

Thursday, 16 June 2011

Lesson 12 PHP file download Script

Retweet this button on every post blogger
File download in PHP is quite easy we have to just scan our directory from which we want to download files
this procedure could be understand more easily by this example;

here we assume that the folder(directory) we want to download file is uploaded_files/ ,


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File download in PHP</title>
</head>

<body>
<h1>PHP file download.</h1>
<table cellpadding="5" cellspacing="5">
<thead><th>File</th><th>Download</th></thead>
<?php
$path = "uploaded_files/"; // the path for the folder.
if (file_exists($path))
 {
    $files = scandir($path);
for($i=2; $i<sizeof($files); $i++)
{
  ?>
  <tr><td><?php echo $files[$i] ?></td><td><a href="<?php echo $path.$files[$i]; ?>"><img src="dl.gif" /></a></td></tr>
  <?php
 }
}
?>
</table>
</body>
</html>
This script simply output a table with file name and download image.

Monday, 13 June 2011

Lesson 11PHP file upload.

Retweet this button on every post blogger
File upload to server computer is a very task to do in PHP to see how it happens lets see a example.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File upload using PHP</title>
</head>
<?php
if(isset($_POST['submit']))
{
     if(isset($_FILES['upload']['name']))
{
    echo "<b>Attributes of file upload:</b><br/>";
echo "<b>File name:</b>" .$_FILES['upload']['name'];
echo "<br/><b>File type:</b>" .$_FILES['upload']['type'];
echo "<br/><b>File Size:</b>" .$_FILES['upload']['size']."bytes";
echo "<br/><b>File Temp:</b>" .$_FILES['upload']['tmp_name'];
echo "<br/><b>File error:</b>" .$_FILES['upload']['error'];

$path1 = $_FILES['upload']['tmp_name'];
$path2 = "uploaded_files/".$_FILES['upload']['name'];
if($_FILES['upload']['type']=="image/pjpeg" || $_FILES['upload']['type']=="image/gif" || $_FILES['upload']['type']=="text/plain" || $_FILES['upload']['type']=="application/x-php"  || $_FILES['upload']['type']=="application/msword")
{
move_uploaded_file($path1,$path2);
echo "<br/>file uploaded to server.";
}
else
echo "<br/><b>select only jpeg,gif,text or  php files to upload.</b>";
}
else
echo "No file choosed.";

}

?>
<body>
<form name="form" method="post"  action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<h1>File upload using PHP</h1>
<center>
<table>
<tr>
<td>Choose file</td><td><input type="file" name="upload"  /></td>
</tr>

<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="upload"  /></td></tr>
</table>

</center>
</form>
</body>
</html>
 1.Where uploaded file folder created at the server holds the user uploaded files.
2.To upload a file the HTML input type must be "file"
3. form enctype="multipart/form-data" must be set that shows that form data must be send as MIME file encoded as binary file.
4. Uploaded file parameters  should use $_FILE global array  to retrieve different file abstract
5. There are five different parameters associated with it. these are ,
    file name
   file type
  file size
 file tmp_name which is temporary storage of file uploaded to server.
file error.

what we to do simply move our file from temporary storage to path  specified by the developer.

Lesson 10 file system using PHP.

Retweet this button on every post blogger
The task is to input a drive name ,folder name , file name, file contents and file extension from the user and save it into the server hard drive.we will learn some php file handling function here.
Program :
<?php
/*php  file system scipt */
if(isset($_POST['submit'])) {
   $errors=''; //an null string
   if ($_POST['folder']=="") {
   $errors.= "<li>Please give a folder name</li>";
    }
 
    if ($_POST['file]=="") {
   $errors.= "<li>Please give a file name</li>";
    }
 
    if ($_POST['text]=="") {
   $errors.= "<li>Please give a file contents</li>";
    }
 
 
   if ($errors=='') {
   $path = $_POST['drive']."/".$_POST['folder'];
   if  (!file_eixsts( $path)) {
   mkdir($path);
   }
  $file_path = $path."/".$_POST['file'].$_POST['ext'];


    if  (!file_eixsts( $file_path)) {
    $fp = fopen($path,"w");  //opening file in write mode at the given path and return a pointer to it.
    fwrite($fp,$_POST['text']); // writing file to directory
   fclose($fp);
   echo "Your file has benn saved.";
   echo "<br/>";
    }


   else
   echo "file exists already, try again";
}
else
echo "<ul>".$errors."</ul>";


?>


<html>
<head>
<title>PHP file handling</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="form"><
<center>
<table>
<tr>
<td>Drive name</td><td><select name="drive">
<option name="c:\">C:\</option>
<option name="d:\">D:\</option>
</select></td>
</tr>

<tr>
<td>Folder name</td><td><input type="text" name="folder" /></td>
</tr>


<tr>
<td>File name</td><td><input type="text" name="file" /></td>
</tr>


<tr>
<td>File contents</td><td><textarea name="text" cols="4" rows="15"></textarea></td>
</tr>


<tr>
<td>File type</td><td><select name="ext">
<option name=".txt">*.txt</option>
<option name=".html">*.html</option>
<option name=".ppt">*.ppt</option>
<option name=".doc">*.doc</option>

</select></td>
</tr>


<tr>
<td>&nbsp;</td><td><input type="submit" name="submit" value="save" /></td>
</tr>
</table>
</center>
</form>
</body>
</html>

Friday, 10 June 2011

Lesson 9 : Post back in PHP

Retweet this button on every post blogger
The method of page post back is quite  easy concept it trip back  on the page on which our code has been placed or in another terms we can say page call itself  for further operation.
Simple example of PHP post back : 
<?php
/*
php code for handling post back.
*/
if(isset($_POST['submit']))
{
    $first = $_POST['fname'];
    $last = $_POST['lname'];
   echo "Full nmae : ".$first." ".$last;
}

?>

<html>
<head><title>Handling post back in PHP</title></head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?> " method="post" name="form">
<center>
<table>
<tr>
<td>first name</td><td><input type="text" name="fname" /></td>
<tr><td>last  name</td><td><input type="text" name="lname" /></td></tr>
<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="go.."</td></tr>
</tr>
</table>
</center>
,</form>
</body>
</html >

 this simple program defining PHP post back as by checking in the starting of the program for posted array variable submit if it got it setted then the further script will  execute .

Another simple example on PHP post back with checkbox input : 
<?php
if(isset($_POST['submit']))
{
    $firstdigit = $_POST['fdigit'];
   $lastdigit = $_POST['ldigit'];
 
  if(isset($_POST['add']))
  {
        $sum =  $firstdigit + $lastdigit ;
  }
 
   if(isset($_POST['mul']))
  {
        $multi =  $firstdigit * $lastdigit ;
  }  
  

}


?>


<html>
<head>
<title>PHP post back</title>
</head>
<body>
<table>
<tr>
<td>First digit</td><td><input type="text" name="fdigit" /></td>
</tr>
<tr>
<td>Second digit</td><td><input type="text" name="sdigit" /></td>
</tr>
<tr>
<td>&nbsp;</td><td>Add<input type="checkbox" name="add" <?php if(isset($_POST['add'])) echo "checked"; ?> />Multiply<input type="checkbox" name="mul" <?php if(isset($_POST['mul'])) echo "checked"; ?> /></td>
</tr>
<tr><td>&nbsp;</td><td><input type="submit" name="submit" value="process" /></td></tr>

<tr>
<td>Results</td>
<td>&nbsp;</td>
</tr>



<tr>
<td>Addition</td>
<td><?php if(isset($sum)) echo $sum; ?></td>
</tr>


<tr>
<td>Multipliaction</td>
<td><?php if(isset($multi)) echo $multi; ?></td>
</tr>


</table>
</body>
</html>

Thursday, 2 June 2011

Lesson 8 : PHP form handling

Retweet this button on every post blogger
Sending form data from one page to another for further processing in an quite simple task in PHP, By setting up only form input type name attribute we can extract them at the server side using PHP global array.
Some example global  array in PHP which we often use in form handling are :

$_POST[]
$_GET[]
$_SERVER[]
$_REQUEST[]
$_COOKIE[]

The global arrays are all associative arrays. This means the value is associated with a name that is the index key for the contents and, sensibly, describes what the value represents. For instance,$_SERVER["SCRIPT_NAME"] contains the URL path to the current page.

Sometimes you can also access the values of the array directly by variable name. This varialbe name is the same as the index key for the array. Thus, the variable name for $_SERVER["SCRIPT_NAME"] would be$SCRIPT_NAME. this can be achieve by extracting the array. 

I think this is enough for any beginner. lets look at the example.
page1.php
<html>
<head><title>PHP from handling.</title></head>
<body>
<form action = "page2.php" method="post">
<center>
<table>
<caption>General info</caption>
<tr>
<td>First Name</td><td><input  type="text" name="fname" /></td>
</tr>
<tr>
<td>Last Name</td><td><input  type="text" name="lname" /></td>
</tr>
<tr>
<td>Address</td><td><input  type="text" name="add" /></td>
</tr>
<tr><td>&nbsp;</td><td><input  type="submit" name="submit"  value="Go.."/></td></tr>

</table>
</center>
</form>
</body>
</html> 
                                                                    --Output--
page2.php
<html>
<head><title>PHP from handling.</title></head>
<body>
<center>
<table>
<caption>General info</caption>
<tr>
<td>First Name</td><td><?php echo $_POST['fname']; ?></td>
</tr>
<tr>
<td>Last Name</td><td><?php echo $_POST['lname']; ?></td>
</tr>
<tr>
<td>Address</td><td><?php echo $_POST['add']; ?></td>
</tr>
</table>
</center>
</body>
</html>   
                                       
                                                                   --Output--
 for sake of simplicity we also extract $_POST[] array as extract($_POST);, and simply use the form input names as POSTED variables in pag2.php.


































Wednesday, 1 June 2011

Lesson 7 include and require

Retweet this button on every post blogger

The include() statement includes and evaluates the specified file.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

An example :-
vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

require()

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.


require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include()statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.



Tuesday, 31 May 2011

Lesson 6 : Object Oriented PHP

Retweet this button on every post blogger
PHP is object oriented programming language it includes in PHP since PHP4 and improved to full object model in PHP5 which provide visibilty, absract, and final classes and methods additional magic methods ,interfaces, cloning and typehinting.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object.


An example of simple class : - 
<html>
<head><title>Object oriented PHP </title></head>
<body>
<?php
class example 

{
   public $var1;
  public $var2;


   function getmultiply() 
  {
     $multi = $this->var1*$this->var2;
    return $multi;
  }


}
?>



<?php
$obj = new example(); ///creting class object.
$obj->var1 = 2;
$obj->var2 = 3;
echo $obj->getmultiply();
?>
</body>
</html>



output : - 
6


To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation.


access specifiers : -
there are basically three types of access specifier in PHP
1. public - data member and methods defined as public are available to use within and outside of the class.


2. protected - data member and methods defined as protected are available only to use in child classes .


3. private -  data member and methods defined as private are available only to use within the  class itself that defines it .


in the example above define class variables $var1 $var2 are public data member. 


Inheritence : -
inheritence is a greate concept of oop programming which gives reusability and allows child classes to use existing methods and data member of the parent class in child class.


parent class :- class from which we are inheriting methods and data mmeber. methods and data members must be defined as public or protected.


child class :- class in which we are  inheriting parent class .


for inherit a class within the child class we use a keyword called extends.


An example of inheritence :- 



<html>
<head><title>Object oriented PHP </title></head>
<body>
<?php
class example 
{
   public $var1;
  public $var2;

   function getmultiply() 
  {
     $multi = $this->var1*$this->var2;
    return $multi;
  }
}

class   add extends example
{
   function addme()
      $sum = $this->var1+$this->var2; // data member form example class.
     return $sum;
}
?>

$child = new  add()
$child->var1 = 2;
$child->var2 = 3;
echo  $child->
addme();


</body>
</html>
output :- 5

Abstract class :--
 An abstract is a class incomplete class which can not be instantiated , it is required for an class to be abstract that it must contain at least one method within it defined as abstract. An abstract method is nothing but only declaration  of the method and its implementation within the second class which inherit it. 
        
<html>
<head><title>Object oriented PHP </title></head>
<body>
<?php
abstract class example 
{
   public $var1;
  public $var2;

   function getmultiply() 
  {
     $multi = $this->var1*$this->var2;
    return $multi;
  }
abstract public function getdivide(); ///only declaration of 
}

class   add extends example
{
   function addme()
      $sum = $this->var1+$this->var2; // data member form example class.
     return $sum;

   function 
getdivide()


  {

      $divide  = $this->var1/$this->var2;

       return $divide;

  }

}
?>
<?php 
$child = new  add()
$child->var1 = 2;
$child->var2 = 3;
echo  $child->
addme();

echo "<br/>";

echo $child->
getdivide();

?>


</body>
</html>