Friday, June 25, 2010

How to connect SQLite in PHP

Introduction

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions.

This allows developers to create code which is portable across many databases and platforms. and this Focus on data abstraction rather than database abstraction


LIst of Databases supported by PDO


* MS SQL Server (PDO)

* Firebird/Interbase (PDO)

* IBM (PDO)

* Informix (PDO)

* MySQL (PDO)

* Oracle (PDO)

* ODBC and DB2 (PDO)

* PostgreSQL (PDO)

* SQLite (PDO)

* 4D (PDO)


Here I am giving the setps to connect SQLite database in php before you start setting up u need to enable the extension=php_pdo_sqlite.dll and
extension=php_sqlite.dll (in case php 5 >) or php_pdo.dll then restart your apache server


Step1 : connect to the SQLite databse using PDO. By using PDO the database creation becomes even easier. Simply specify the path to the database file and it will be loaded. If the database file does not exist, PDO will attempt to create it.

<?php
try {
         // connect to SQLite from PDO database
         $dbh = new PDO("sqlite:/path/to/database.db");

}
catch(PDOException $e)
{
         echo $e->getMessage();//this getMessage throws an exception if any
     
}
?>

Step2 :now run the query by using the database object created
$result = $dbh->query($query);
while($row = $result->fetch())
{
         print("$row["fieldname"]");
}

Sample code
Here i am Creating database name "database" and the table TestTable.

<?php
try {

         // connect to SQLite from PDO database

         $dbh = new PDO("sqlite:database.db");

}
catch(PDOException $e)

{
          echo $e->getMessage();        
}
    $query = 'CREATE TABLE TestTable ' .
     '(Title TEXT, Name TEXT, Year INTEGER)';

    $result = $dbh->query($query);

if(!$dbh->query($query))
{
       echo "table not created ";

}

$query =
             'INSERT INTO TestTable (Title, Name, Year) ' .
            'VALUES ("Mr", "Rakesh", 2010); ' .

              'INSERT INTO TestTable (Title, Name, Year) ' .
             'VALUES ("Mr", "Ram", 2008)' ;
if(!$dbh->query($query))
{
            echo "row not inserted ";
}
$query = "SELECT * FROM TestTable";

if($result = $dbh->query($query))

{

      while($row = $result->fetch())
     {
             print("Title: {$row['Title']}  " .
             "Name: {$row['Name']}".
             "Year: {$row['Year']}");
      }
}
else
{
          echo "not selected ";
}

Saturday, June 5, 2010

How to fix the FlexiGrid Height and Width dynamically based on the screen resolution

FelxiGris is Lightweight but rich data grid with resizable columns and a scrolling data to match the headers, plus an ability to connect to an xml based data source using Ajax to load the content
To Set up the flexigrid click here

Once your flexigrid setup is over you may face problem of fixing the height and width of the grid which is defined as constant value in setup . instead of setting it as constant value you can make it as dynamic
Here I am giving the steps to make it as dynamic
Step 1.
If you flexigrid component is calling inside the div tag or table tag follow the height and width as in terms of percentage
Step 2.
Sample table structure where u can place the flexigrid table
<table > border=”0” height=”100%” width=”100%”>
<tr height=”22”><td height=”20”>header if any</td></tr>
<tr height=”100%”><td height=”100%”> <!—100% to take rest of space -->
<div id=”flexigridDiv” ><table id="flex1"></table></div>
</td>
</tr>
</table>
Step3.
Then inside the flexigrid calling function set the height as
$("#flex1").flexigrid({
url: url,
dataType: 'json',
colModel : [
{display: name, name : 'idx', width : 40, sortable : true, align: 'center'},
{display: 'age', name : 'age', width : 100, sortable : true, align: 'left'},
{display: 'Description', name : 'description', width : 120, sortable : true, align: 'left'}
],
sortname: "idx",
sortorder: "desc",
usepager: true,
useRp: true,
rp: 20,
showTableToggleBtn: true,
onSubmit: addFormData,
height: $(“ #flexigridDiv”).innerHeight(); //this takes the height of the 2nd tr dynamically
});

Saturday, March 13, 2010

POPUP window using simple jquery function

The attractive and simple popup window with full control over on by using jquery component
Here I am giving the basic html part ,css,and the javscript part for getting the popup window
Note: please download the jquery component from the site http://docs.jquery.com/Downloading_jQuery and include that component into your html header

Step1
Copy paste the below html part for displaying the button and the div content
Put the following code inside the body tag
 
Step2
Copy paste the following css inside the header part with style sheet tag
This css can be edited as per your requirement
------------------------------------------------------------------------
#backgroundPopup{ display:none;position:fixed;_position:absolute; /* for internet explorer*/
height:100%;width:100%;top:0;left:0;background:#000000;border:1px solid #cecece;z-index:1; }

#maincontent{display:none; position:fixed; _position:absolute; /* hack for internet explorer 6*/ height:384px; width:608px; background:#FFFFFF; border:2px solid #cecece; z-index:2;padding:12px; font-size:13px; }

#Closepopup{ font-size:14px; line-height:14px; right:6px; top:4px; position:absolute; color:#6fa5fd; font-weight:700; display:block; }
-----------------------------------------------------------------------

Step3
Copy paste the following javascript inside the header tag with script tag
This javascript function are editable as per your requirement

      $(document).ready(function(){
         //LOADING POPUP
         //Click the button event!
        $("#openpopup").click(function(){
        //centering with css
          aligncenter();
       //load popup
         loadPopup();
       });
       //CLOSING POPUP
      //Click the x event...
      $("#Closepopup").click(function(){
          disablePopup();
     });
     //Click out event..
        $("#backgroundPopup").click(function(){

     });
     //Press Escape event...
       $(document).keypress(function(e){
           if(e.keyCode==27 && popupStatus==1){
              disablePopup();
           }
      });
})
//0 means disabled; 1 means enabled;
var popupmain = 0;
//loading popup with jquery component
function loadPopup(){
       //loads popup only if it is disabled
       if(popupmain==0){
            $("#backgroundPopup").css({
                "opacity": "0.7"
            });
       $("#backgroundPopup").fadeIn("slow");//to fade in the content slowly
       $("#maincontent").fadeIn("slow");//main pop up content opens slowly
       popupmain = 1;//changing once the popup is opened fro the next time popup content
     }
}
//disabling popup with jQuery magic!
function disablePopup(){
         //disables popup only if it is enabled
        if(popupmain==1){
                 $("#backgroundPopup").fadeOut("slow");
                $("#maincontent").fadeOut("slow");
               popupmain = 0;
          }
}
//centering popup
function aligncenter(){
         //request data for centering
          var windowWidth = document.documentElement.clientWidth;
          var windowHeight = document.documentElement.clientHeight;
         var popupHeight = $("#maincontent").height();
          var popupWidth = $("#maincontent").width();
         //centering
        $("#maincontent").css({
              "position": "absolute",
              "top": windowHeight/2-popupHeight/2,
               "left": windowWidth/2-popupWidth/2
        });
        //only need force for IE6
        $("#backgroundPopup").css({
        "height": windowHeight
     });
}
Step 4
Now on click of “click here” button you should get the popup window , disabling the background from any click operation and click on the X mark on top right to close the window or press escape button from the keyboard to close the popup window

Demo:
The following image shows you the popup window output

VTU Results for all semesters exams

VTU results Please enter your USN below



Enter the VTU University Seat No:


For Revaluation VTU results Please enter you USN below.



Enter the VTU University Seat No:

VTU resluts

VTU Reval resluts

Tuesday, December 8, 2009

Mysql-PHP in JAVA using quercus resin server in windows

Mysql connection with the quercus resin server from java module

In the previous post you can see the installation of the resin server with the hello world example now in this post you can see the mysql connection with the java module in quercus resin server

Here I want to show that basic php-mysql application can be make it run with the java module using resin server where you can write db connection in java and make use of connection in php pages

List of API or jar files required to execute this .

1.mysql-connector-java-5.1.5-bin.jar (from mysql’s download page) (http://www.mysql.com/products/connector/)
2. quercus.jar (in the quercus zip from caucho)
3. resin-util.jar (in the quercus zip from caucho)
4. script-10.jar (in the quercus zip from caucho)
Put all this jar files in lib folder

Follow the steps to setup the mysql-php-java module

Step 1.
Inside \resin-pro-3.1.9\webapps\ROOT\WEB-INF folder create web.xml with the following code

servlet-class="com.caucho.quercus.servlet.QuercusServlet"/>



jdbc:mysql://localhost:3306/test
root





Step2.
inside \resin-pro-3.1.9\webapps\ROOT\WEB-INF\classes\example create java class file with the

DBconnect .java

package example;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import com.caucho.quercus.module.AbstractQuercusModule;
public class DBconnect extends AbstractQuercusModule{
/**
* The DataSource for the table.
*/
private DataSource _ds = null;
/**
* Sets the data source.
*/
public void setDataSource(DataSource ds)
{
_ds = ds;
}
/**
* Initializes the reference to the CourseBean home interface.
*/
public String test_fun()
{
return "Hello raki ";
}
public String conn_db()
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String rtn_str=" ";

try
{
conn=DriverManager.getConnection("jdbc:mysql://localhost/testdb?" + "user=root"); //change testdb to your database name
stmt = conn.createStatement();
//rtn_str+="\n middle \n";
if (stmt.execute("SELECT * FROM table")) {
rs = stmt.getResultSet();
while(rs.next())
{
String filed1 = rs.getString("filed1");//change filed1 to your table column
String filed2 = rs.getString("filed2");//change filed2 to your table column
rtn_str+= " filed1:-"+ filed1 + " filed2:- " + filed2 +"
";
//rtn_str+=" \n"+rs.getInt(1)+"\n";
}
}

}
catch(Exception e)
{
}


//rtn_str+="<\pre>";
return rtn_str;
}


}

Step3.
inside \resin-pro-3.1.9\webapps\ROOT\WEB-INF\classes\META-INF\services create the following file with name “com.caucho.quercus.QuercusModule” put the content

example.DBconnect


step4.
Now inside \resin-pro-3.1.9\webapps\ROOT create the php page which calls the java module with name php_mysql_java.php

echo "your module data comes here “."
";
echo conn_db ().”
";

?>


Step 5.
Now run the hello_world.php from the URL as
http://localhost:8080/ php_mysql_java.php

You should see “your module data comes here
The data base values should comes here ”

PHP in JAVA using quercus resin server in windows

Quercus is Caucho Technology's fast, open-source, 100% Java implementation of the PHP language

Quercus is written for Resin, a Java application server.

If your using resin server then you can able to call java module from the php page . but here I am showing running of php file with the tomcat server using java compiler
The interesting thing is you can import java libraries or module from php page.
Follow the setps to install the quercus (resin server)

Step1.
Download the resin server installation package from the this page(http://www.caucho.com/download/)

Step2.
Unzip downloaded file and put it inside the your c drive

Step3.
dont forgot to install JDk(1.5 or >) and set the environment path for the same

Step4.
when you open resin main folder(\resin-pro-3.1.9) you can see http file click on it and that will start your resin server
NOTE:-in case if you’re not able to run the resin server
Step1.you can see the setup file inside the main resin folder run that folder it will ask you some configuration

Step2.click on the apache server option and give the root path to the apache where you have installed apache so that it can able to access the apache http.conf file form there.

Step3.then press apply and then start http file it should start your resin server now

Step4. In worst case you can able to start the resin sever from the command prompt eit the following command . change the path in to your resin main folder and then run this command” cd:\resin>java –jar lib/resin.jar start” .

Step5.now open browser and type http://localhost:8080/ you should see the default page of the resin server if that comes your installation is correct. then proceed further

Step 6. Inside \resin-pro-3.1.9\webapps\ROOT\WEB-INF folder create web.xml with the following code


servlet-class="com.caucho.quercus.servlet.QuercusServlet"/>




Step7.
inside \resin-pro-3.1.9\webapps\ROOT\WEB-INF\classes\example create java class file with the

HelloWorld .java

package example;

import com.caucho.quercus.module.AbstractQuercusModule;

public class HelloWorld extends AbstractQuercusModule {
/*
** Notice the careful use of the naming
** convention hello_test. This is done
** in order to prevent name collisions
** among different libraries.
*/
public String hello_test(String name)
{
return "Hello, " + name;
}
}

Step8.
inside \resin-pro-3.1.9\webapps\ROOT\WEB-INF\classes\META-INF\services create the following file with name “com.caucho.quercus.QuercusModule” put the content

example.Helloworld

step9.
Now inside \resin-pro-3.1.9\webapps\ROOT create the php page which calls the java module with name hello_world.php

echo "your module data comes here “."
";
echo hello_test("World")."
";

?>

Step 10.
Now run the hello_world.php from the URL as
http://localhost:8080/hello_world.php

You should see “your module data comes here
hello world”

Thursday, November 5, 2009

Virtual Host concept in apache configuration and proxy Apache server

The term Virtual Host refers to the practice hosting more than one website in server on one machine. For example in single sever they can maintain multiple website with different host name as www.example1.com and www.example2.com, without requiring the user to know any extra path information.
How to configure virtual host in different scenarios in your http.config file is defined here

++The common basic virtual host setting
# Virtual hosts
NameVirtualHost 192.1.1.1:80

serverName localhost
Document localhost

In the above through IP address and the port number you can set the sever name in localhost and the
Root Document files path to select root path of the site

++Get information about the requests being processed by the server and the
configuration of the server.

Required modules: 1.mod_status (for the server-status handler),
2.mod_info (for the server-info handler)

SetHandler server-status
Order deny,allow
Deny from all
Allow from .localhost


++ Settings for hosting different languages.

Required modules: mod_mime, mod_negotiation
DefaultLanguage and AddLanguage allows you to specify the language of a document. You can then use content negotiation to give a browser a file in a language the user can understand.

DefaultLanguage nl
AddLanguage ca .ca
AddLanguage cs .cz .cs
AddLanguage da .dk
AddLanguage de .de
AddLanguage el .el
AddLanguage en .en
AddLanguage eo .eo

++If you want to maintain multiple domains/hostnames on your machine

Most configurations use only name-based virtual hosts so the server doesn't need to worry about IP addresses. This is indicated by the asterisks in the directives below.

ServerAdmin webmaster@dummy-host.localhost
DocumentRoot /www/docs/dummy-host.localhost
ServerName dummy-host.localhost
ServerAlias www.dummy-host.localhost
ErrorLog logs/dummy-host.localhost-error_log
CustomLog logs/dummy-host.localhost-access_log common



ServerAdmin webmaster@dummy-host2.localhost
DocumentRoot /www/docs/dummy-host2.localhost
ServerName dummy-host2.localhost
ErrorLog logs/dummy-host2.localhost-error_log
CustomLog logs/dummy-host2.localhost-access_log common




Proxy Apcahe server

An ordinary forward proxy is an intermediate server that sits between the client and the origin server. In order to get content from the origin server, the client sends a request to the proxy naming the origin server as the target and the proxy then requests the content from the origin server and returns it to the client. The client must be specially configured to use the forward proxy to access other sites.

Required modules:proxy_module , proxy_http_module , proxy_balancer_module



ServerName dummy-host.localhost
ErrorLog logs/dummy-host.localhost-error_log

ProxyRequests Off
proxyPreserveHost on


Order deny,allow
Allow from all


ProxyPass / dummy-host
ProxyPassReverse / dummy-host


Order deny,allow
Allow from all


Thursday, October 29, 2009

Installing PHPUNIT2 on Windows system

The following post gives u a detail information about installation of PHPUNIT2 into your wamp server on windows system

Step1. Check your wamp has installed properly on windows system. If it is then open wamp folder and go to the php folder and you should find go-pear.bat file

Step2. open command prompt and go to php directory in wamp

C:\> cd wamp\php

If your wamp structure is different then check for following path

C:\>cd wamp\php\php5.5

But here I am following the wamp\php path for installation. if yours is different than please follow as in your wamp instead of “wamp\php”






Step3.
Run go-pear.bat batch file from this place for complete installation of pear into your wamp php server

C:\cd wamp\php>go-pear.bat

Here it will ask you for some conformation if you don’t know then go with the default selection like [system | local]system:”select system here”

Complete the process like this with all default selection

Step4. once the installation is completed run PEAR_ENV.reg file from this place so that environment variable can be created to the for the user running wamp server. Then only your able to access pear files anywhere in the document root folder

NOTE:if your unable to create environment variable then manually you can create with following steps

Click on system properties->select advanced->Environment variables

Here you can add directory path variable “ c:\wamp\php

Step5. Once your pear setup is over you must register your phpunit channel with the pear registry

C:\wamp\php>pear channel-discover pear.phpunit.de

Step6. Once the register is over now your able to install all supporting packages from the phpunit channel

C:\wamp\php>pear install pear/phpunit2

Then it may ask you to install all supporting packages for phpuint like

C:\wamp\php>pear install pear/benchmark

C:\wamp\php>pear install pear/console_Getopt

Step7. Now you will find phpunit folder under php\pear folder where all subfolder with all utilities will be there now your phpunit as configured and its ready to use in your project

Thursday, October 8, 2009

Creating recursive folders in linux server through php script

Creating recursive folders in linux server through php script

while creating directory inside your root folder or in any folder through php script you should take care of the following steps.

which may gives you problem by not creating folder under any root folder

In some linux server if your warrings are off then it won’t give warring msg if any following error raise

this type of problem you may get when you’re trying to create folder recursively

Here I am giving the list of problem

1)permission

2)owner permission

3)group permission

4)most important safe mode ON in linux server

If your having problem of not creating folder under any root folder or under any other folder (permission problem)

-pls check the root permission for the folder under which your trying to create dir through php

Or through php itself you can able to change the permission for the folder like this

$chmod_value = chmod(“/root/folder/”,0755);

-don’t giv full permission for the source folder where your trying to create max 755 is enough.

-if your not able to create due to owner permission then

-pls check under which owner your trying to create the folder and you can change the owner of the folder to the current logged in

chown (“root/folder/”,"owner_name");//giv the proper owner name

--if your not able to create due to group permission then

-pls check under which group your trying to create the folder and you can change the group of the folder to the current logged in

chgrp (“root/folder/”,"group_name");//giv the proper group name

- if you’re not able to create due to safe mode on

-if your trying to create recursive folders in linux server then u must take care of safemode setting inside your config file

-if your server safemode is ON then your unable to create recursive folders

It wont alow you to change the permission through php script by default it vl take its own apache as user and group as apache

-to overcome this prblem you can try this by changing the safemode off through php like this

ini_set("safe_mode",0);

-if your using .htaccess file at ur root level then you can try the by setting

Default safe_mode off ;

-in worst condition if the above 2 way don’t work then you have to switch of the safe mode directly inside your apache server configure so by this your php should be able to create folder inside linux server


Tuesday, October 6, 2009

Uploading Multiple Files in PHP without ajax or jquery

Uploading Multiple Files in PHP without ajax or jquery
Here iam giving simple and very efficient php multiple file uploader in single submit with the option of deleting uploaded files from the list
And this uploader works in both LE and Firefox very well
While uploading multiple file after adding files into the list before uploading u can able to alter the list in this uploader, and in list only the file names will be visible
And inside javascript u can change the images and buttons based on your require
The Steps installing this uploader into ur php file pls follow the steps below
Step 1
Paste this following javascript inside ur html file or in separate javascript file which should be include in html
function MultiSelector( list_target, max ){
// Where to write the list
this.list_target = list_target;
// How many elements?
this.count = 0;
// How many elements?
this.id = 0;
// Is there a maximum?
if( max ){
this.max = max;
} else {
this.max = -1;
};


/**
* Add a new file input element
*/
this.addElement = function( element ){
// Make sure it's a file input element
if( element.tagName == 'INPUT' && element.type == 'file' ){ // Element name -- what number am I?
element.name = 'ufile[]';//this u can set if your making use of array in the list
element.id='ufile[]'; // Add reference to this object
element.multi_selector = this;
// What to do when a file is selected
element.onchange = function(){
// New file input
var new_element = document.createElement( 'input' );
new_element.type = 'file';
new_element.size = '48';
// Add new element
this.parentNode.insertBefore( new_element, this );
// Apply 'update' to element
this.multi_selector.addElement( new_element );
// Update list
this.multi_selector.addListRow( this );
// Hide this: we can't use display:none because Safari doesn't like it
this.style.position = 'absolute';
this.style.left = '-1000px';
};
// If we've reached maximum number, disable input element
if( this.max != -1 && this.count >= this.max ){
element.disabled = true;
};
// File element counter
this.count++;
// Most recent element
this.current_element = element;
} else {
// This can only be applied to file input elements!
alert( 'Error: not a file input element' );
};
};
/**
* Add a new row to the list of files
*/
this.addListRow = function( element ){
// Row div
var new_row = document.createElement( 'div' );
// Delete button to add the button
var new_row_button = document.createElement( 'input' );
new_row_button.type = 'button';
new_row_button.value = 'Delete';
new_row_button.align = 'absbottom';
new_row_button.style.cursor = 'hand';
// Delete image instead of button you can put image with this following code
/*var new_row_button = document.createElement('img');
new_row_button.src = images/image_namegif';
new_row_button.alt = 'Delete';
new_row_button.height = '14';
new_row_button.align = 'absbottom';*/
// References
new_row.element = element;
// Delete function
new_row_button.onclick= function(){
// Remove element from form
this.parentNode.element.parentNode.removeChild( this.parentNode.element );
// Remove this row from the list
this.parentNode.parentNode.removeChild( this.parentNode );
// Decrement counter
this.parentNode.element.multi_selector.count--;
// Re-enable input element (if it's disabled)
this.parentNode.element.multi_selector.current_element.disabled = false;
// Appease Safari
// without it Safari wants to reload the browser window
// which nixes your already queued uploads
return false;
};
// Add button
new_row.appendChild(new_row_button);
// Set row value
var arr = element.value.split("\\");
var out_count =arr.length;
if(navigator.appName == "Microsoft Internet Explorer") {
var new_label = document.createElement('label');
new_label.align = 'absmiddle';
new_label.innerHTML = ' '+arr[out_count - 1];
//new_row.innerHTML += arr[out_count - 1];
new_row.appendChild(new_label);
//new_row.innerHTML = new_row_button;
}
else
{
var new_label = document.createElement('label');
new_label.align = 'absmiddle';
new_label.innerHTML = ' '+element.value;
new_row.appendChild(new_label);
}
//new_row.appendChild(new_row_button);
// Add it to the list
this.list_target.appendChild( new_row );
};
};
Step 2
Paste this code in place of where you want to display the upload browse button and the list of file uploaded
Hav form with action
<form action="upload.php"   method="post" id="uploadfrm" name=" uploadfrm " enctype="multipart/form-data">
<div >
<input id="ufile[]" size="48" type="file" value="" name="file_1" />
</div>
<div id="files_list"> </div>//here you can see the list of files uploaded 
</form>
Step 3
In upload.php you can access this files data in this way
if (count($_FILES ['ufile']['name'])) {
for($i=0;$i
{
$root_path= //root path of the upload folder where you created
$path[$i]= $root_path."/upload/".$_FILES['ufile']['name'][$i];//where you want to upload the your  files(path) $file_names[$i] = $_FILES['ufile']['name'][$i];
$copy_done[$i] = copy($_FILES['ufile']['tmp_name'][$i], $path[$i]);
}
if($copy_done)
{
    echo "uploaded"; 
}
}

Thursday, September 10, 2009

How to get full url path in php by using server parameter

From $_server variable has several parameter related to get the url information in different format

Getting the url information from the $server depends on in which way you want to display information like getting only server host or server request url ,server port etc…..

Here iam giving some information about getting url information in different ways in different cases.

-To get server host name

.echo $_SERVER['HTTP_HOST'];

-To get server name

echo $_SERVER['SERVER_NAME'];

-To get server port

echo $_SERVER["SERVER_PORT"];

By using the above predefined variables we can able to get the full u rl of the present page in which ur working

Here is example to get the full url in php

/**
*
* @to get the full url of page on which ur working
*
*/
function getUrlAddress()
{
/*** check for https is on or not ***/
$url = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
/*** return the full address ***/
return $ url .'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}

/*** example usage ***/
echo getUrlAddress ();

Wednesday, August 19, 2009

Naming Conventions & Coding Standards in PHP.

Naming Conventions & Coding Standards in PHP.

Naming Conventions

  • PHP Files
    • Names should be short & descriptive (either in German or English).
    • If the module is handling a DB table, then its name should be same as the table itself omitting ‘table_’.
  • Templates
    • Name of template should be identical to the name of the php module with change in extension to ‘.tpl’ or .html
    • If there is more than one template, then use postfix like ‘_xyz” to the template name. Eg : ‘user_header.tpl’ & ‘user_position.tpl’ or .html
  • Functions
    • Function name should be in English.
    • Only Lower case letters to be used.
    • Should contain 2 parts
      • Appropriate Verb ( Eg. get)
      • Manipulated Object( Eg. Product )
      • Eg : get_students() | get_ students _name()
      • A short description about the output and input parameters should also accompany the function description.
  • Classes
    • Class Names
      • Camel Case convention should be followed.
      • Beginning letter should be in Caps
    • Variable Names
      • Local variables : All small letters with ‘_’ for separation.
      • Local Methods : Camel Case with beginning letter in ‘Small Caps’.

  • Variable Names inside PHP code/modules
    • Use Lower Case Letters only
    • Use ‘_’ for separation.

Coding & Documentation

1. A DocBlock / Documentation Block.

A basic DocBlock looks like this:

/**

*

**/

To document any function, place the DocBlock immediately before the function declaration.

A DocBlock contains three basic segments in this order:

· Short Description

· Long Description

o The Short Description starts on the first line, and can be terminated with a blank line or a period. A period inside a word (like example.com or 0.1 %) is ignored. If the Short Description would become more than three lines long, only the first line is taken. The Long Description continues for as many lines as desired and may contain html markup for display formatting. Here is a sample DocBlock with a Short and a Long Description:

§ Example :

/**

* return the date of Easter

*

* Using the formula from "Formulas that are way too complicated for anyone to

* ever understand except for me" by Irwin Nerdy, this function calculates the

* date of Easter given a date in the Ancient Mayan Calendar, if you can also

* guess the birthday of the author.

*/

· Tags

o Optionally, you may enclose all paragraphs in a

tag.

o Be careful, if the first paragraph does not begin with

, phpDocumentor will assume that the DocBlock is using the simple double line break to define paragraph breaks as in Example:

/**

* Short desc

*

*

Long description first sentence starts here

* and continues on this line for a while

* finally concluding here at the end of

* this paragraph

* This text is completely ignored! it is not enclosed in p tags

*

This is a new paragraph

*/

2. TAGS

/*

* Here are the tags:

*

* @abstract

* @access public or private

* @author author name

* @copyright name date

* @deprecated description

* @deprec alias for deprecated

* @example /path/to/example

* @exception Javadoc-compatible, use as needed

* @global type $globalvarname

or

* @global type description of global variable usage in a function

* @ignore

* @internal private information for advanced developers only

* @param type [$varname] description

* @return type description

* @link URL

* @name procpagealias

or

* @name $globalvaralias

* @magic phpdoc.de compatibility

* @package package name

* @see name of another element that can be documented,

* produces a link to it in the documentation

* @since a version or a date

* @static

* @staticvar type description of static variable usage in a function

* @subpackage sub package name, groupings inside of a project

* @throws Javadoc-compatible, use as needed

* @todo phpdoc.de compatibility

* @var type a data type for a class variable

* @version version

*/

3. Other Considerations

a. Usage of space

i. For enhancing readability, spaces should be used between each function name , command , commas and brackets

b. Prevent lines with excess length.

i. Code should be readable in editors with normal number of character ( 80 or 100 max). Horizontal scrolling should be avoided.

ii. Example

$sql = sprintf ("SELECT %s FROM %s WHERE %s='%s'",

$field_value,

$table,

$field_index,

$id

);

And not like this one:

$sql = sprintf ("SELECT %s FROM %s WHERE %s='%s'", field_value, $table,$field_index, $id);

c. Positioning Of Brackets

i. If Statement

If (“ “)

{

….

….

}

Else

{

}

ii. Switch Statement

Switch(“ “)

{

case 1 :

line 1;

line 2;

break;

case 2 :

line 3;

line 4;

break;

}

d. Documenting Rule

i. Do not comment on things which are obvious.

ii. As a matter of principle , the variable name should give away the meaning of the same eliminating unwanted documentation.

iii. Make clear why a certain action is taken. As shown in the example :

/**

* An unregistered customer calls up a product

**/

If (isset($_SESSION["user"])==false)

{

/**

* All unregistered caller gets a temporary customer ID. If he registered during his

* session, all statistical data is to be rewritten on to his correct ID.

**/

if (isset ($_SESSION["tmpStudentID "])==false)

{

....

....

}

}

e. Documentation of implementation details and background

i. Its recommended that the developer documents the background details which are taken up for granted.

/**

* We are using a timer of seconds, risking the problem of two customers using the

* same function at the same second, not to be identified.

**/

$time = time();

$ StudentrID = $time;

$_SESSION["tmpStudentID"]=$StudentrID;