Tuesday, November 10, 2009

Using PHP Namespaces

PHP 5.3 introduces a much requested feature for object-oriented programmers: namespaces. At the time of this writing, version 5.3 of PHP was in development, but is planned on being released in the near future.

One of the purposes object-oriented programming is to remove ambiguous development and data access items. This basically means identifying common functionality and creating the most reusable framework possible, typically in the form of classes. When creating this functionality, you will begin to have issues with naming conventions and narrowing down functionality even further. To resolve this scoping issue, namespaces allow you to contain those bits of code even more.


It seems that PHP will be going with a similar namespace setup as C++. In order to declare a namespace, you will use the “namespace” keyword.

PHP
  1. namespace MyNamespace;
  2. class Test {
  3. public function hello() {
  4. echo ‘Hello’;
  5. }
  6. }
  7. ?>

The declaration above simply states that all elements contained in this script will be referenced with the “MyNamespace” namespace. You will need to place the “namespace” declaration at the top of the script.

In order to use a portion of functionality within this script, we will use the Scope Resolution Operator and instantiate the “Test” class.

  1. // Requiring the namespace file is a good indication that you don’t need to use namespaces, but this is only an example!
  2. require(‘the_file_above.php’);
  3. $test = new MyNamespace::Test();
  4. $test->hello();
  5. // Prints ‘hello’
  6. ?>

Monday, October 19, 2009

LAMP - Apache, PHP, MySQL Installation easy steps

Some like it binary some like compiling, I am amongst the compiling ones..
here are some easy steps that I usually follow to compile Apache, PHP to my machine.

  1. Apache
    1. ./configure --prefix=/usr/local/apache2.2.6 --enable-so --enable-proxy --enable-rewrite --enable-expires --enable-headers --enable-deflate --enable-ssl
    2. sudo make
    3. sudo make install
    4. cd /usr/local
    5. ln -s apache2.2.6 apache
    6. cd
  2. PHP
    1. ./configure --prefix=/usr/local/php5.2.5 --with-mysql=/usr/local/mysql --with-apxs2=/usr/local/apache/bin/apxs --with-pdo-mysql --with-gd --with-jpeg-dir=/usr/lib --with-png-dir=/usr/lib
    2. sudo make
    3. sudo make install
    4. cd /usr/local
    5. ln -s php5.2.5 php
    6. Configure Apache httpd.conf for PHP module
      1. LoadModule php5_module modules/libphp5.so
      2. AddType application/x-httpd-php .php .phtml

Wednesday, October 7, 2009

Advanced Php Questions...

1. What is Indexing and how we create describe his merits and demerits.

Indexes are created on a per column basis. If you have a table with the columns: name, age, birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries, then you would need to create an index for employeeID. When you create this index, MySQL will build a lookup index where employeeID specific queries can be run quickly. However, the name, age and birthday queries would not be any faster.

Indexes are something extra that you can enable on your MySQL tables to increase performance,c but they do have some downsides. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.

If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below. We have created two fields: name and employeeID (index).
CREATE TABLE employee_records (name VARCHAR(50),employeeID INT,
INDEX (employeeID) );

2. Upload the file use Ajax.

3. How to save the other image in ur server dynamically.

4. If we have a n number of category in table, how we find the main parent of the last node.

5. Describe the sequence of mysql query,
(a) primary->subquery->sub-sub query
(b) primary-> primary-> subquery.
(c) sub-subquery->subquery-> primary.

6. if a table contain a salary of employee, how following query return a result.
select salary form employee_table order by salary desc.
select salary form employee_table order by salary 2 desc.

give the answer.

7. what is NDB & how it configure?

8. If one table holds the data of employee, so what is return by following query after remove the parenthesis.

select (salary*2)+(3/salary)*(1.3+salary) from employee.

9. what is session and describe its default life time & how we increase it?

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

default time is 1440 seconds and after make a changes in php.ini session life time change.

10. difference between Innodb and Myissam table engine?
Innodb support the foreign key constraints myissam not.
Innodb support the rollback and commit myissam not.
myissam is default Engine of mysql it occupies less memory in compare of Innodb.

11. Diff between Primary key and Unique key.
primary must be integer and notnull, and only 1 primary in key in one table, many unique key assign in one table and not limitation of integer and not null.

12. MySql Injection

13. Crontab
cron is a unix, solaris utility that allows tasks to be automatically run in the background at regular intervals by the cron daemon. These tasks are often termed as cron jobs in unix , solaris.
Crontab (CRON TABle) is a file which contains the schedule of cron entries to be run and at specified times.

14.how we find a size of file
filesize($filename);

15. what is union n mysql explain with example;
SQL UNION allows you to combine two or more result sets from select statements into a single result set. The usage of using SQL UNION is as follows:

SELECT statement UNION [DISTINCT | ALL] SELECT statement UNION [DISTINCT | ALL]

The column list of each individual SELECT statement must have the same data type. By default the UNION removes all duplicated rows from the result set even if you don’t explicit using DISTINCT after the UNION keyword. If you use UNION ALL explicitly, the duplicated rows will remain in the result set. Let’s practice with couples of examples which use SQL UNION. Suppose you want to combine customers and employees into one, you just perform the following query:
SELECT customerNumber id, contactLastname name FROM customers UNION SELECT employeeNumber id,firstname name FROM employees
Here is the excerpt of the output
    id  name          
------ ---------------
103 Schmitt
112 King
114 Ferguson
119 Labrune
121 Bergulfsen
124 Nelson
125 Piestrzeniewicz
128 Keitel
129 Murphy
131 Lee
In order to use ORDER BY to sort the result you have to use it after the last SELECTstatement. It would be the best to parenthesize all the SELECT statements and place ORDER BY after the last one. Suppose we use the want to sort the combination of employees and customers in the query above we can do as follows:
(SELECT customerNumber id,contactLastname name FROM customers) UNION (SELECT employeeNumber id,firstname name FROM employees) ORDER BY name,id
First it orders the result set by name and then by id What if we don’t use alias for each column in the SELECT statement? MySQL uses the column names in the first SELECTstatement as the label of the result therefore you can rewrite the query above as follows:
(SELECT customerNumber, contactLastname FROM customers) UNION (SELECT employeeNumber, firstname FROM employees) ORDER BY contactLastname, customerNumber
or you can also use the column position in the ORDER BY clause like following query
(SELECT customerNumber, contactLastname FROM customers) UNION (SELECT employeeNumber,firstname FROM employees) ORDER BY 2, 1


Thursday, July 9, 2009

Find Duplicate Data

1. how to find a duplicate records from table?
Lets the table name is report and its have a two field, id and type.
type contain a numbers of duplicate records...

first retrieve the all records from table:
select type,id from report;








typeid
php1
php2
mysql3
mysql4
lamp5
lamp6


use command:
select count(type), id from report group by type having count(type)>1;

get the records like this:






count(type)id
21
22
23


the above table explains the id 1,2,3 contain the 2 number of duplicates data.

Thursday, June 18, 2009

Php Interview Question

1.what is Register_global.
Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables. register globals allows you to have $_GET['test'] and $_POST['test'] equate to $test.

2. How many type of error in php.
notice, warning, fatal error.

3.What is abstraction.
a concept or idea not associated with any specific instance,
Php 5 introduce a abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation..
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.

4. Interface and Abstract Class.
Abstract class have a abstract method keyword its inherit with child class with extends keyword

Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Interfaces are a common set of methods those can be implemented across various types of classes dealing with various objectives. In case of an abstract class, its something like a factory containing set of a process.

5.Pattern in PHP.
abstract factory : set of method to make vaious object.
builder : make and return one object various ways.
factory method: methods to make and return components of one object various ways.
prototype: make a object by the cloning of object which u said as a prototype.
singletone : the class distributes the class of itself.

6. find the difference between two dates
$date1 = "2007-03-24";
$date2
= "2009-06-26";

$diff
= abs(strtotime($date2) - strtotime($date1));
//abs absolute value

$years
= floor($diff / (365*60*60*24));
$months
= floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days
= floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf
("%d years, %d months, %d days\n", $years, $months, $days);

7.What is Exception Handling.
With php 5 came a new object oriented way to dealing with error.
Exception Handling is used to change the normal flow of code execution if a specified
error is occur.

This is what normally happens when an exception is triggered:

  • The current code state is saved
  • The code execution will switch to a predefined (custom) exception handler function.
  • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code.

We will show different error handling methods:

  • Basic use of Exceptions
  • Creating a custom exception handler
  • Multiple exceptions
  • Re-throwing an exception
  • Setting a top level exception handler

Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.


function checkNumber($number){
if($number>1){
throw new Exception ("Value must be 1 or less then 1");
}
return true;
}
try{
checkNumber(2);
print "the try message is display";
}
catch(Exception $number){
echo "Message".$number->getMessage();
}

8.How validate email address except regular expressions.

filter_var($email, FILTER_VALIDATE_EMAIL);

function ($email){

if(!filter_var($email, FILTER_VALIDATE_EMAIL)){

print $email. "is not valid email id";

}

else{

print "email valid";

}


Saturday, December 13, 2008

How to [mount_point cannot contain the following How to [mount_point cannot contain the following chacharacters: newline, G_DIR_SEPARATOR (usually /)]

Open gconf-editor in terminal:

$ gconf-editor
In the left panel:
Goto:

System -> Storage -> volumes

Here you will see the mount point you specified for the device.
Change it to just a single word (OR just remove it :) )
Thats it. Replug your device.

Enjoy!!!

EDIT:
1. Do not use sudo for this purpose.
See this comment by Anonym... (Thanx to Anonym) for detail.

2. Sometimes instead of System -> Storage -> volumes you may also get System -> Storage -> drives , depending upon what you messed up. The rest process is same.

Wednesday, September 17, 2008

Abstract v/s Interface

There are lost of discussion on the internet about the Interface vs Abstract class. Also, as base class whether we have to use interface, abstract class or normal class.

I am trying to point out few considerations on which we can take decision about Interface vs Abstract class vs Class.

Abstract Class vs Interface

I am assuming you are having all the basic knowledge of abstract and interface keyword. I am just briefing the basics.

We can not make instance of Abstract Class as well as Interface.

Here are few differences in Abstract class and Interface as per the definition.

Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface can only contain public methods, this is the nature of interface.

//Abstarct Class

public abstract class Vehicles

{

private int noOfWheel;

private string color;

public abstract string Engine

{

get;

set;

}

public abstract void Accelerator();

}

//Interface

public interface Vehicles

{

string Engine

{

get;

set;

}

void Accelerator();

}

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed.

We use abstract class and Interface for the base class in our application.

This is all about the language defination. Now million doller question:

How can we take decision about when we have to use Interface and when Abstract Class.

Basicly abstact class is a abstract view of any realword entity and interface is more abstract one. When we thinking about the entity there are two things one is intention and one is implemntation. Intention means I know about the entity and also may have idea about its state as well as behaviour but don’t know about how its looks or works or may know partially. Implementation means actual state and behaviour of entity.