PHP Magic Methods

MAGIC METHODS

1.Why magic methods ?

Ans:

In PHP,  a variable can take any form depending on the data passed to it. Also PHP automatically creates variable and assigns values to it even if the variables are not defined. But in Object Oriented Programming all the data members/methods needs to be defined. To solve some of these problems in OOPS environment magic methods have been introduced in PHP5.

  1. Magic methods are member function that is available for all instance of class.
  2. Magic method stars with __(double underscore), like: __get () ,__set()
  3. Magic methods are always declared as PUBLIC.

LIST of MAGIC METHODS used in PHP 5 :

__get() , __set() , __autoload , __sleep() , __wakeup() , __construct() , __destruct() , __isset() , __unset() , __clone , __call ,__toString()

1. __construct() :- This methods gets called whenever an object of a class is instantiated.

2. __destruct() :–  This methods gets called whenever an object of a class is destroyed or object goes out of scope.

3. __set() :–  This methods get automatically called whenever you assigns data to a undefined attributes of an class in PHP 5. With this method the programmer can keep track on the variables which are not defined inside the class.

    Syntax:

    < ?

    function __set($data,$value){

    //$data – holds the name of the undefined attributes

    //$value – holds the value assigned to the undefined attributes.

    }

    ?>

    Example:

    < ?
    class magicmethod{
                   function __set($data,$value)
                   {
                                   echo "Error assigning values to undefined attributes";
                                   echo "attributes Called:".$data;
                                   echo "Value assigned to attributes:".$value;
                   } 
    }
    $a = new magicmethod();
    $a->setData = 20;
    ?>
    In Above example : 

      Output:
      Error assigning values to undefined attributes
      attributes Called:setData
      Value assigned to attributes:20

      Explain:

      In the magicmethod class setData is not defined so the php compiler excutes __set() magic method and displays error message.

      And  assigned value 20 to an attribute setData of magicmethod class.

      5. __get() :- This methods get automatically called when you try to retrieves the data of undefined attributes of an class in PHP 5.

        Syntax:

        function __get($data)
        {
             //$data holds the name of the undefined attributes getting called.
        }
          
        Example:
        < ?
        class magicmethod
        {
           function __get($data)
           {
               echo "Error accessing undefined attributes";
               echo "attributes Called:".$data;
           }
        }
         
        $a = new magicmethod();
        echo $a->setData;
         
        ?>
         
        Output:
        Error accessing undefined attributes
        attributes Called:setData
         
        Explain: 
        a.echo an attribute setData of magicmethod class.
        b.But in the magicmethod class setData is not defined so the php compiler excutes __get() magic method and displays error message 
        
        6.__cal() :- The __call Magic method in PHP5 get called when accessing an undeclared or undefined methods of an class. With this magic method the programmer can keep track on the undeclared method which are not defined inside the class.

          Syntax:

          < ?
          function __call($data,$argument)
          {
                         //$data holds the name of the undefined method getting called.
                  //$argument holds the argument passed to the method.
          }
          ?>

          Example:

          < ?
          class magicmethod
          {
           
                         function __call($data,$argument)
                         {
                                         echo "Error accessing undefined Method";
                                         echo "Method Called: ".$data;
                                         echo "Argument passed to the Method: ".$argument;
                         }
           
          }
           
          $a = new magicmethod();
          echo $a->setData();  //Calling setData method
           
          ?>

          Output:
          Error accessing undefined Method
          Method Called: setData
          Argument passed to the Method: Array (Array of the Argument Passed)

          Explain:

          1.trying to call setData method of magicmethod class.

          2.Now in the magicmethod class setData is not defined so the php compiler excutes __call() magic method and displays error message.


          6. __sleep() :-  This methods gets called when you serialize the object in PHP 5. Serializing is required to pass complex data across the network or PHP pages. It is also used to store data(files, database, cookies etc).

            Syntax:

            < ?
            function __sleep()
            {
                           ...
                           return serialised data;
            }
            ?>

            Example:

            < ?
            class magicmethod
            {
                           function __sleep()
                           {
                                           echo "Performing Clean-Up Operation Before Serializing Data ";
                                           return array("Serialized Data","1","2","3");
                           }
            }
            $a = new magicmethod();
            $serializedata = serialize($a);
            echo $serializedata;
            ?>

            Output:
            Performing Clean-Up Operation Before Serializing Data
            O:11:”magicmethod”:4:{s:15:”Serialized Data”;N;s:1:”1″;N;s:1:”2″;N;s:1:”3″;N;}

            Explain:

            a.trying to serialize the object of magicmethod class.

            b.Now the PHP Compiler calls the __sleep() Magic method which return an array having the serialized values

            7.__wakeup() :- This methods gets called when the object is about to be unserialized in PHP 5. This method allows us to restore the serialized data to its normal form.

            Syntax:

            function __wakeup()
            {
                           ...
            } 
            

            Example:

            < ?
            class magicmethod
            {
                           private $setName;
                           function __sleep()
                           {
                                           echo "Performing Clean-Up Operation Before Serializing Data ";
                                           $this->setName = "Hello World!!!";
                                           return array(setName);
                           }
             
                           function __wakeup()
                           {
                                           echo "Performing Clean-Up Operation Before Unserializing Data ";
                                           echo $this->setName;
                           }
            }
            $a = new magicmethod();
            $serializedata = serialize($a);
            $serializedata1 = unserialize($serializedata);
            ?>

            Output:
            Performing Clean-Up Operation Before Serializing Data
            Performing Clean-Up Operation Before Unserializing Data
            Hello World!!!

            Explain:

            a.trying to serialize the object of magicmethod class

            b.Now the PHP Compiler calls the __sleep method which return an array having the serialized values

            c. After serialize data, i am calling the unserialize function; now the PHP compiler will call the __wakeup method which contains the original data that was serialized .

            8. __autoload():-This methods get automatically called whenever you try to load an object of class which resides in separate file and you have not included those files using include,require and include_once. To use this method it is mandatory to the PHP filename as that of the class name because this methods accepts the class name as the argument.

              Syntax:

              < ?
                 function __autoload($classname)
                 {
                    require($classname.".php");
                 }
              //$classname is the name of the Class.
              ?>

              Example:

              //magicmethod1.php

              < ?
                  class magicmethod1
                  {
                      function __construct()
                      {
                          echo "MagicMethod1 Class Called";
                      }
                  }
                ?>
              <?php
                  function __autoload($classname)
                  {
                      include $classname.".php"; //Here $classname=magicmethod1
                  }
               
                  $a = new magicmethod1();
              ?>

              Output: MagicMethod1 Class Called

              Explain:

              trying to create an object of magicmethod1 class, but i have not included the magicmethod1.php so PHP compiler calls the __autoload() method which include that magicmethod1.php file.

              9.__clone() :- PHP5 has introduced clone method which creates an duplicate copy of the object. __clone methods automatically get called whenever you try to call clone methods in PHP 5. This operator does not creates a reference copy.

                In PHP 5 when you assign one object to another object creates a reference copy and does not create duplicate copy. This would create a big mess as all the object will share the same memory defined for the object. To counter this PHP 5 has introduced clone method

                Example:

                //without cloning

                < ?
                class Animal
                {
                   public $name;
                   public $legs;
                 
                   function setName($name)
                   {
                               $this->name = $name;
                   }
                 
                   function setLegs($legs)
                   {
                               $this->legs = $legs;
                   }
                }
                 
                $tiger = new Animal();
                $tiger->name = "Tiger";
                $tiger->legs = 4;
                 
                $kangaroo = $tiger;
                $kangaroo->name = "Kangaroo";
                $kangaroo->legs = 2;
                 
                echo $tiger->name."---".$tiger->legs;
                echo "<br />".$kangaroo->name."---".$kangaroo->legs;
                ?>

                Output:
                Kangaroo—2
                Kangaroo—2

                Explanation:

                • Here i have created an $tiger object of Animal class
                • Created another variable $kangaroo and assigned $tiger to $kangaroo
                • After echo it print the details entered last because both the variables are referring to the same memory location

                Example:

                //with __Clone

                < ?
                class Animal
                {
                   public $name  ;
                   public $legs;
                 
                   function setName($name)
                   {
                               $this->name = $name;
                   }
                 
                   function setLegs($legs)
                   {
                               $this->legs = $legs;
                   }
                 
                   function __clone()
                   {
                               echo "<br />Object Cloning in Progress";
                   }
                }
                 
                $tiger = new Animal();
                $tiger->name = "Tiger";
                $tiger->legs = 4;
                 
                $kangaroo = clone $tiger;
                $kangaroo->name = "Kangaroo";
                $kangaroo->legs = 2;
                 
                echo "<br />".$tiger->name."---".$tiger->legs;
                echo "<br />".$kangaroo->name."---".$kangaroo->legs;
                ?>

                Output:
                Object Cloning in Progress
                Tiger—4
                Kangaroo—2

                Explanation:

                • Here i have created an $tiger object of Animal class
                • Created another variable $kangaroo having clone of $tiger. This calls the __clone magic method
                • After echo it print the details entered by individual object as both of them are referring to separate object and memory location

                The above technique of cloning discussed is called shallow copy. There are other techniques called Deep Copy wherein you create duplicate copy of objects referring to other objects etc.

                10. __toString() :- __toString method is called when PHP needs to convert class instances into strings, for example when echoing:

                <?php

                class SomeClass {
                public function __toString() {
                return ‘someclass’;
                }
                }

                $obj = new SomeClass();
                echo $obj;
                //will output ‘someclass’

                ?>

                11. __isset() :- This methods get automatically called whenever you try to check the existence of the undeclared attributes of the class using isset function of PHP.

                12. __unset() :- This methods get automatically called whenever you try to check the destroy or clear an undeclared attributes of the class using unset function of PHP

                Advertisements

                PHP & ORACLE

                PHP &  ORACLE

                Introduction to ORACLE : –  Oracle DB is well known for scalability , reliability and features.It is a leading DB and is available on many platforms.

                Oracle Terminology:  

                1. 1.       Databases and Instances :-  Oracle databases store and retrieve data. Each database consists of one or more data files. An Oracle database server  consists of an Oracle database and an Oracle Instance. Whenever an Oracle database server is started , a shared memory region SGA(System Global Area) is allocated and Oracle background processes are started. Combination of background processes and SGA is called an Oracle Instance.   
                2. 2.       Tablespaces :-  Tablespaces are logical unit of data storage made up of one or more datafiles. 
                3. 3.       Schemas:- A Schema is a collection of database objects such as tables and indexes. Typically, a single DB contains multiple schemas. Multiple Application can use same DB without any conflicts by using   different schemas. Instead of using a CREATE DATABASE command for new application , use CREATE USER to create a new schema in the database. 

                PHP ORACLE EXTENSIONS

                PHP has several extensions that let application use Oracle DB. Database access  and abstract library in each extension of PHP   is fundamentally similar. The differences are in  support for advanced features and programming methodology.

                If you want to make full use of Oracle features and need high performance, PHP OCI8 extension  has to be used. PHP OCI8 is a main ORACLE Extension.

                If you want database independence , use PHP PDO(data object) or ADOdb extension for database abstraction.

                 

                PHP Oracle Extensions

                1.Oracle (Not recommended)

                2.OCI8

                3.PDO

                4.ODBC

                PHP Oracle extensions are written in C  and linked into PHP Binary.

                 

                 

                OCI8 Extension :- OCI8 Extension is recommended extension to use. It is used in PHP 3,4 and 5.

                Example:

                <?php

                $con=oci_connect(‘dbname’,’passwd’,’localhost/XE’);

                $s=oci_parse($con,’select * from User’);

                oci_execute($s);

                While($res=oci_fetch_array($s,OCI_ASSOC)){

                echo $res[‘name’];

                }

                ?>

                HOW TO GET OCI8 EXTENSION

                Bundle Containing OCI8 Location and Current Release
                1. PHP Source Code
                http://www.php.net/downloads.phpphp-5.2.7.tar.bz2
                1.  PECL Source Code
                http://pecl.php.net/package/oci8oci8-1.3.4.tgz
                1.  Zend Core for Oracle 2.5
                http://www.oracle.com/technology/tech/php/zendcore/ZendCoreForOracle-v2.5.0-Linux-x86.tar.gz

                ZendCoreforOracle-v.2.5.0-Windows-x86.exe

                   

                Oracle has cross-version compatibility, that means if PHP OCI8 is linked with Oracle10g  Client Libraries, then it can able to connect with Oracle database  8i,9i,10g,11g. If OCI8 is linked with oracle 11g client libraries then it can able to connect with Oracle9iR2 onwards  .

                Full OCI8 functionality may not be available unless Oracle client libraries and database servers are latest version.

                OCI8 and Oracle Compatibility Matrix

                Software Bundle PHP Version OCI8 VersionIncluded Oracle Client Libraries Usablewith OCI8
                PHP Release Source Code Current release is 5.2.7 OCI8 1.2.5 8i, 9i, 10g, 11g
                PECL OCI8 Source Code Builds with PHP 4.3.9onwards Latest release isOCI8 1.3.4 9iR2, 10g, 11g
                Zend Core for Oracle 2.5 Includes PHP 5.2.5 OCI8 1.2.3 Inbuilt Oracle Database 10g client
                       

                ORACLE DATABASE XE :-

                Oracle database XE (Oracle 10g ) is available on 32-bit Windows and Linux platform.Oracle DatabseXE is available on Oracle network http://otn.oracle.com/xe

                Oracle Database XE has a browser based management interface, Oracle Application Express.

                Installing Oracle Database XE on Windows

                REFER :- http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

                REFERENCE :- http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

                WEB 2.0

                WEB 2.0 :-

                It is a second generation of web developement and design that aims to facilitate communications , secure information sharing , interoperability (means ability of diverse systems and organisation to work together ) and collaboration on world wide web . Web 2.o concepts useerd in host services , applications such as social networking sites , blogs, video sharing sites , wikis .

                web 2.0 encourages interactivity and interconnectivity. Web 2.0 websites allow user to do more than just retreiving information . These sites provide controll to user so that they can own data and exercise controll over data.

                Web 2.0 is often feature a rich , user friendly based on AJAX, Open laszlo , Flex and other rich media.

                The Characteristic of web 2.0 are : rich user experience , user participation , dynamic content , metadata(Metadata (meta data, or sometimes metainformation) is “data about other data”, of any sort in any media. metadata would document data about data elements or attributes, (name, size, data type, etc) and data about records or data structures (length, fields, columns, etc) and data about data (where it is located, how it is associated, ownership, etc.)) , web standards and scalability(scalability is a desirable property of a system, a network, or a process, which indicates its ability to either handle growing amounts of work in a graceful manner, or to be readily enlarged).




                PHP Interview Question

                1. What are the differences between GET and POST methods in form submitting, give the case where we can use get and we can use post methods?


                On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.


                On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.


                GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.


                2. Who is the father of php and explain the changes in php versions?


                Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.


                3. How can we submit from without a submit button?


                We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example:


                4. How many ways we can retrieve the date in result set of mysql Using php?


                As individual objects so single record or as a set or arrays.


                5. What is the difference between mysql_fetch_object and mysql_fetch_array?


                MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array.


                6. What is the difference between $message and $$message?


                They are both variables. But $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.


                7. How can we extract string ‘abc.com ‘ from a string ‘http://info@a…’ using regular _expression of php?


                We can use the preg_match() function with “/.*@(.*)$/” as the regular expression pattern. For example: preg_match(“/.*@(.*)$/”,”http://info@abc.com&#8221;,$data); echo $data[1];


                8. How can we create a database using php and mysql?


                PHP: mysql_create_db()

                Mysql: create database;


                9. What are the differences between require and include, include_once?


                File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.


                10. Can we use include (“abc.php”) two times in a php page “makeit.php”?


                Yes we can include..


                11. What are the different tables present in mysql, which type of table is generated when we are creating a table in the following

                syntax: create table employee(eno int(2),ename varchar(10)) ?


                Total 5 types of tables we can create


                1. MyISAM


                2. Heap


                3. Merge


                4. InnoDB


                5. ISAM


                6. BDB

                MyISAM is the default storage engine as of MySQL 3.23.


                12. Functions in IMAP, POP3 AND LDAP?


                Please visit:

                http://fi2.php.net/imap

                http://uk2.php.net/ldap


                13. How can I execute a php script using command line?


                Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.

                Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.


                14. Suppose your ZEND engine supports the mode Then how can u configure your php ZEND engine to support mode ?


                If you change the line: short_open_tag = off in php.ini file. Then your php ZEND engine support only mode.


                15. Shopping cart online validation i.e. how can we configure the paypals?


                16. What is meant by nl2br()?


                nl2br — Inserts HTML line breaks before all newlines in a string string nl2br (string); Returns string with ‘’ inserted before all newlines. For example: echo nl2br(“god bless\n you”) will output “god bless \n you” to your browser.


                17. Draw the architecture of ZEND engine?


                18. What are the current versions of apache, php, and mysql?


                PHP: php5.1.2

                MySQL: MySQL 5.1

                Apache: Apache 2.1


                19. What are the reasons for selecting lamp (Linux, apache, mysql, php) instead of combination of other software programs, servers and operating systems?


                All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. Php is more faster that asp or any other scripting language.


                20. How can we encrypt and decrypt a data present in a mysql table using mysql?


                AES_ENCRYPT () and AES_DECRYPT ()


                21. How can we encrypt the username and password using php?


                You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Password”);

                We can encode data using base64_encode($string) and can decode using base64_decode($string);


                22. What are the features and advantages of OBJECT ORIENTED PROGRAMMING?


                One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns.

                For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.


                23. What are the differences between PROCEDURE ORIENTED LANGUAGES and OBJECT ORIENTED LANGUAGES?


                Traditional programming has the following characteristics:


                Functions are written sequentially, so that a change in programming can affect any code that follows it.

                If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested.

                Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system.


                Object-Oriented programming takes a radically different approach:


                Code and data are merged into one indivisible item – an object (the term “component” has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around “date”) The object would contain all information and functionality for that thing (A date

                object it may contain labels like January, February, Tuesday, Wednesday. It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system. The information within an object is encapsulated (or hidden) from the rest of the system.

                A system is composed of multiple objects (i.e., date function, reports, order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages.

                OO programming languages include features such as “class”, “instance”, “inheritance”, and “polymorphism” that increase the power and flexibility of an object.


                24. What is the use of friend function?


                Friend functions

                Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class whichnames them as a friend, as if they were themselves members of that class.

                A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.


                class mylinkage

                {

                private:

                mylinkage * prev;

                mylinkage * next;


                protected:

                friend void set_prev(mylinkage* L, mylinkage* N);

                void set_next(mylinkage* L);


                public:

                mylinkage * succ();

                mylinkage * pred();

                mylinkage();

                };


                void mylinkage::set_next(mylinkage* L) { next = L; }


                void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }


                Friends in other classes


                It is possible to specify a member function of another class as a friend as follows:


                class C

                {

                friend int B::f1();

                };

                class B

                {

                int f1();

                };


                It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.


                class A

                {

                friend class B;

                };


                Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.


                25. What are the differences between public, private, protected, static, transient, final and volatile?

                element Class Interface

                Data field Method Constructor

                modifier top level nested top level nested

                (outer) (inner) (outer) (inner)

                final yes yes no yes yes no no

                private yes yes yes no yes no yes

                protected yes yes yes no yes no yes

                public yes yes yes yes yes yes yes

                static yes yes no no yes no yes

                transient yes no no no no no no

                volatile yes no no no no no no


                26. What are the different types of errors in php?


                Three are three types of errors:


                1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although, as you will see, you can change this default behaviour.


                2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.


                3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behaviour is to display them to the user when they take place.


                27. What is the functionality of the function strstr and stristr?


                strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr(“user@example.com”,”@”) will return “@example.com”.

                stristr() is idential to strstr() except that it is case insensitive.


                28. What are the differences between PHP 3 and PHP 4 and PHP 5?


                Go read the release notes at http://php.net.


                29. How can we convert asp pages to php pages?


                You can download asp2php front-end application from the site http://asp2php.naken.cc.


                30. What is the functionality of the function htmlentities?


                Answer: htmlentities — Convert all applicable characters to HTML entities

                This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.


                31. How can we get second of the current time using date function?


                $second = date(“s”);


                32. How can we convert the time zones using php?


                33. What is meant by urlencode and urldocode?


                urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode(“10.00%”) will return “10%2E00%25?. URL encoded strings are safe to be used as part of URLs.

                urldecode() returns the URL decoded version of the given string.


                34. What is the difference between the functions unlink and unset?


                unlink() deletes the given file from the file system.

                unset() makes a variable undefined.


                35. How can we register the variables into a session?


                We can use the session_register ($ur_session_var) function.


                36. How can we get the properties (size, type, width, height) of an image using php image functions?


                To know the Image type use exif_imagetype () function

                To know the Image size use getimagesize () function

                To know the image width use imagesx () function

                To know the image height use imagesy() function


                37. How can we get the browser properties using php?


                38. What is the maximum size of a file that can be uploaded using php and how can we change this?


                You can change maximum size of a file set upload_max_filesize variable in php.ini file


                39. How can we increase the execution time of a php script?


                Set max_execution_time variable in php.ini file to your desired time in second.


                40. How can we take a backup of a mysql table and how can we restore it.?

                Answer: Create a full backup of your database: shell> mysqldump –tab=/path/to/some/dir –opt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir

                The full backup file is just a set of SQL statements, so restoring it is very easy:


                shell> mysql “.”Executed”;

                mysql_close($link2);


                41. How can we optimize or increase the speed of a mysql select query?



                42. How many ways can we get the value of current session id?

                ans:-

                session_id() returns the session id for the current session.


                43. How can we destroy the session, how can we unset the variable of a session?

                Ans:-

                session_unregister — Unregister a global variable from the current session

                session_unset — Free all session variables


                44. How can we destroy the cookie?

                Ans:-

                Set the cookie in past


                45. How many ways we can pass the variable through the navigation between the pages?

                Ans:-

                GET or QueryString and POST


                46. What is the difference between ereg_replace() and eregi_replace()?

                Ans:-

                eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.


                47. What are the different functions in sorting an array?

                Ans:-

                Sorting functions in PHP,

                asort-http://www.php.net/manual/en/function.asort.php

                arsort-http://www.php.net/manual/en/function.arsort.php

                ksort-http://www.php.net/manual/en/function.ksort.php

                krsort-http://www.php.net/manual/en/function.krsort.php

                uksort-http://www.php.net/manual/en/function.uksort.php

                sort-http://www.php.net/manual/en/function.sort.php

                natsort-http://www.php.net/manual/en/function.natsort.php

                rsort-http://www.php.net/manual/en/function.rsort.php


                48. How can we know the count/number of elements of an array?

                Ans:-

                2 ways

                a) sizeof($urarray) This function is an alias of count()

                b) count($urarray)

                interestingly if u just pass a simple var instead of a an array it will return 1.

                49. What is the PHP predefined variable that tells the What types of images that PHP supports?


                50. How can I know that a variable is a number or not using a JavaScript?


                51. List out some tools through which we can draw E-R diagrams for mysql.


                52. How can I retrieve values from one database server and store them in other database server using PHP?




                53. List out the predefined classes in php?


                Directory

                stdClass

                __PHP_Incomplete_Class

                exception

                php_user_filter


                54. How can I make a script that can be bilanguage (supports Eglish, German)?


                You can change charset variable in above line in the script to support bilanguage.


                55. What are the difference between abstract class and interface?


                Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.


                Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.


                56. How can we send mail-using JavaScript?


                NO! JavaScript can’t email a form! but, there are alternatives to send the form data to an email address.


                57. How can we repair a mysql table?


                The syntex for repairing a mysql table is

                REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]

                This command will repair the table specified if the quick is given the mysql will do a repair of only the index tree if the extended is given it will create index row by row


                58. What are the advantages of stored procedures, triggers, indexes?


                A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.

                Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.

                Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.


                59. What is the maximum length of a table name, database name, and fieldname in mysql?


                Database name- 64

                Table name -64

                Fieldname-64


                60. How many values can the SET function of mysql takes?


                Mysql set can take zero or more values but at the maximum it can take 64 values


                61. What are the other commands to know the structure of table using mysql commands except explain command?


                describe table_name;




                Please visit this link :

                http://placementhelper.blogspot.com/2007/12/php-interview-questions-1.html

                for lots of PHP questions and answers

                XML database example

                AJAX can be used for interactive communication with a database.


                AJAX Database Example

                In the AJAX example below we will demonstrate how a web page can fetch information from a MySQL database using AJAX technology.


                Select a Name in the Box Below

                Select a User: Peter Griffin Lois Griffin Joseph Swanson Glenn Quagmire

                User info will be listed here.

                This example consists of four elements:

                • a MySQL database
                • a simple HTML form
                • a JavaScript
                • a PHP page

                The Database

                The database we will be using in this example looks like this:

                id FirstName LastName Age Hometown Job
                1 Peter Griffin 41 Quahog Brewery
                2 Lois Griffin 40 Newport Piano Teacher
                3 Joseph Swanson 39 Quahog Police Officer
                4 Glenn Quagmire 41 Quahog Pilot

                The HTML Form

                The example above contains a simple HTML form and a link to a JavaScript:

                <html>
                <head>
                <script src="selectuser.js"></script>
                </head>
                <body>
                <form>
                Select a User:
                <select name="users" onchange="showUser(this.value)">
                <option value="1">Peter Griffin</option>
                <option value="2">Lois Griffin</option>
                <option value="3">Glenn Quagmire</option>
                <option value="4">Joseph Swanson</option>
                </select>
                </form>
                <p>
                <div id="txtHint"><b>User info will be listed here.</b></div>
                </p>
                </body>
                </html>

                Example Explained – The HTML Form

                As you can see it is just a simple HTML form with a drop down box called “users” with names and the “id” from the database as option values.

                The paragraph below the form contains a div called “txtHint”. The div is used as a placeholder for info retrieved from the web server.

                When the user selects data, a function called “showUser()” is executed. The execution of the function is triggered by the “onchange” event.

                In other words: Each time the user changes the value in the drop down box, the function showUser() is called.


                The JavaScript

                This is the JavaScript code stored in the file “selectuser.js”:

                var xmlHttp
                function showUser(str)
                {
                xmlHttp=GetXmlHttpObject()
                if (xmlHttp==null)
                 {
                 alert ("Browser does not support HTTP Request")
                 return
                 }
                var url="getuser.php"
                url=url+"?q="+str
                url=url+"&sid="+Math.random()
                xmlHttp.onreadystatechange=stateChanged
                xmlHttp.open("GET",url,true)
                xmlHttp.send(null)
                }
                function stateChanged()
                {
                if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
                 {
                 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
                 }
                }
                function GetXmlHttpObject()
                {
                var xmlHttp=null;
                try
                 {
                 // Firefox, Opera 8.0+, Safari
                 xmlHttp=new XMLHttpRequest();
                 }
                catch (e)
                 {
                 //Internet Explorer
                 try
                  {
                  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                  }
                 catch (e)
                  {
                  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                 }
                return xmlHttp;
                }

                Example Explained

                The stateChanged() and GetXmlHttpObject functions are the same as in the PHP AJAX Suggest chapter, you can go to there for an explanation of those.

                The showUser() Function

                If an item in the drop down box is selected the function executes the following:

                1. Calls on the GetXmlHttpObject function to create an XMLHTTP object
                2. Defines the url (filename) to send to the server
                3. Adds a parameter (q) to the url with the content of the dropdown box
                4. Adds a random number to prevent the server from using a cached file
                5. Call stateChanged when a change is triggered
                6. Opens the XMLHTTP object with the given url.
                7. Sends an HTTP request to the server

                The PHP Page

                The server page called by the JavaScript, is a simple PHP file called “getuser.php”.

                The page is written in PHP and uses a MySQL databse.

                The code runs a SQL query against a database and returns the result as an HTML table:

                <?php
                $q=$_GET["q"];
                
                $con = mysql_connect(’localhost’, ‘peter’, ‘abc123′);
                if (!$con)
                 {
                 die(’Could not connect: ‘ . mysql_error());
                 }
                
                mysql_select_db(”ajax_demo”, $con);
                
                $sql=”SELECT * FROM user WHERE id = ‘”.$q.”‘”;
                
                $result = mysql_query($sql);
                
                echo “<table border=’1′>
                <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Age</th>
                <th>Hometown</th>
                <th>Job</th>
                </tr>”;
                
                while($row = mysql_fetch_array($result))
                 {
                 echo “<tr>”;
                 echo “<td>” . $row['FirstName'] . “</td>”;
                 echo “<td>” . $row['LastName'] . “</td>”;
                 echo “<td>” . $row['Age'] . “</td>”;
                 echo “<td>” . $row['Hometown'] . “</td>”;
                 echo “<td>” . $row['Job'] . “</td>”;
                 echo “</tr>”;
                 }
                echo “</table>”;
                
                mysql_close($con);
                ?>
                

                Example Explained

                When the query is sent from the JavaScript to the PHP page the following happens:

                1. PHP opens a connection to a MySQL server
                2. The “user” with the specified name is found
                3. A table is created and the data is inserted and sent to the “txtHint” placeholder

                Ajax anh PHP XML example

                AJAX can be used for interactive communication with an XML file.


                AJAX XML Example

                In the AJAX example below we will demonstrate how a web page can fetch information from an XML file using AJAX technology.


                Select a CD in the Box Below

                Select a CD: Bob Dylan Bee Gees Cat Stevens

                CD info will be listed here.

                This example consists of four pages:

                • a simple HTML form
                • an XML file
                • a JavaScript
                • a PHP page

                The HTML Form

                The example above contains a simple HTML form and a link to a JavaScript:

                <html>
                <head>
                <script src="selectcd.js"></script>
                </head>
                <body>
                <form>
                Select a CD:
                <select name="cds" onchange="showCD(this.value)">
                <option value="Bob Dylan">Bob Dylan</option>
                <option value="Bee Gees">Bee Gees</option>
                <option value="Cat Stevens">Cat Stevens</option>
                </select>
                </form>
                <p>
                <div id="txtHint"><b>CD info will be listed here.</b></div>
                </p>
                </body>
                </html>

                Example Explained

                As you can see it is just a simple HTML form with a simple drop down box called “cds”.

                The paragraph below the form contains a div called “txtHint”. The div is used as a placeholder for info retrieved from the web server.

                When the user selects data, a function called “showCD” is executed. The execution of the function is triggered by the “onchange” event.

                In other words: Each time the user changes the value in the drop down box, the function showCD is called.


                The XML File

                The XML file is “cd_catalog.xml“. This document contains a CD collection.


                The JavaScript

                This is the JavaScript code stored in the file “selectcd.js”:

                var xmlHttp
                
                function showCD(str)
                {
                xmlHttp=GetXmlHttpObject()
                if (xmlHttp==null)
                 {
                 alert ("Browser does not support HTTP Request")
                 return
                 }
                var url="getcd.php"
                url=url+"?q="+str
                url=url+"&sid="+Math.random()
                xmlHttp.onreadystatechange=stateChanged
                xmlHttp.open("GET",url,true)
                xmlHttp.send(null)
                }
                
                function stateChanged()
                {
                 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
                 {
                 document.getElementById("txtHint").innerHTML=xmlHttp.responseText
                 }
                }
                function GetXmlHttpObject()
                {
                var xmlHttp=null;
                try
                 {
                 // Firefox, Opera 8.0+, Safari
                 xmlHttp=new XMLHttpRequest();
                 }
                catch (e)
                 {
                 // Internet Explorer
                 try
                  {
                  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                  }
                 catch (e)
                  {
                  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                  }
                 }
                return xmlHttp;
                }

                Example Explained

                The stateChanged() and GetXmlHttpObject functions are the same as in the last chapter, you can go to the previous page for an explanation of those

                The showCD() Function

                If an item in the drop down box is selected the function executes the following:

                1. Calls on the GetXmlHttpObject function to create an XMLHTTP object
                2. Defines the url (filename) to send to the server
                3. Adds a parameter (q) to the url with the content of the input field
                4. Adds a random number to prevent the server from using a cached file
                5. Call stateChanged when a change is triggered
                6. Opens the XMLHTTP object with the given url.
                7. Sends an HTTP request to the server

                The PHP Page

                The server paged called by the JavaScript, is a simple PHP file called “getcd.php”.

                The page is written in PHP using the XML DOM to load the XML document “cd_catalog.xml“.

                The code runs a query against the XML file and returns the result as HTML:

                <?php
                $q=$_GET["q"];
                $xmlDoc = new DOMDocument();
                $xmlDoc->load("cd_catalog.xml");
                $x=$xmlDoc->getElementsByTagName('ARTIST');
                for ($i=0; $i<=$x->length-1; $i++)
                {
                //Process only element nodes
                if ($x->item($i)->nodeType==1)
                  {
                  if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
                    {
                    $y=($x->item($i)->parentNode);
                    }
                  }
                }
                $cd=($y->childNodes);
                for ($i=0;$i<$cd->length;$i++)
                {
                //Process only element nodes
                if ($cd->item($i)->nodeType==1)
                  {
                  echo($cd->item($i)->nodeName);
                  echo(": ");
                  echo($cd->item($i)->childNodes->item(0)->nodeValue);
                  echo("<br />");
                  }
                }
                ?>

                Example Explained

                When the query is sent from the JavaScript to the PHP page the following happens:

                1. PHP creates an XML DOM object of the “cd_catalog.xml” file
                2. All “artist” elements (nodetypes = 1) are looped through to find a name matching the one sent from the JavaScript.
                3. The CD containing the correct artist is found
                4. The album information is output and sent to the “txtHint” placeholder

                AJAX

                AJAX = Asynchronous JavaScript And XML

                AJAX is an acronym for Asynchronous JavaScript And XML.

                AJAX is not a new programming language, but simply a new technique for creating better, faster, and more interactive web applications.

                AJAX uses JavaScript to send and receive data between a web browser and a web server.

                The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change.


                AJAX Is Based On Open Standards

                AJAX is based on the following open standards:

                • JavaScript
                • XML
                • HTML
                • CSS

                The open standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent. (Cross-Platform, Cross-Browser technology)


                AJAX Is About Better Internet Applications

                Web applications have many benefits over desktop applications:

                • they can reach a larger audience
                • they are easier to install and support
                • they are easier to develop

                However, Internet applications are not always as “rich” and user-friendly as traditional desktop applications.

                With AJAX, Internet applications can be made richer (smaller, faster, and easier to use).


                You Can Start Using AJAX Today

                There is nothing new to learn.

                AJAX is based on open standards. These standards have been used by most developers for several years.

                Most existing web applications can be rewritten to use AJAX technology instead of traditional HTML forms.


                AJAX Uses XML And HTTP Requests

                A traditional web application will submit input (using an HTML form) to a web server. After the web server has processed the data, it will return a completely new web page to the user.

                Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.

                With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server (behind the scenes), and by modifying only parts of the web page using JavaScript when the server returns data.

                XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.

                You will learn more about how this is done in the next chapters of this tutorial.


                PHP and AJAX

                There is no such thing as an AJAX server.

                AJAX is a technology that runs in your browser. It uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

                AJAX is a web browser technology independent of web server software.

                However, in this tutorial we will focus more on actual examples running on a PHP server, and less on how AJAX works.