SAMPLE QUESTION PAPER
Q.1) Attempt any FIVE of the following.                                    (10 Marks)
  a) List any four advantages of PHP?
       ANS-
         • PHP is easy to use.
         • PHP is free and open source.
         • PHP is flexible language.
         • PHP supports many databases connectivity’s such as MySQL, Oracle etc.,
         • PHP is platform independent.
         • PHP is loosely typed language.
  b) State the use of str_word_count along with its syntax.
       ANS-
       The str_word_count() is in-built function of PHP. It is used to return information
       about words used in a string or counts the number of words in a string.
       Syntax: str_word_count (string)
       Parameters:
       string specify the string to check.
       return specify the return value of the function.
       <?php
       $a="PHP JAVA";
       echo "The total word is: ".str_word_count($a);
       ?>
  c) Define serialization.
       ANS-
       Serializing an object means converting it to a byte stream representation that can be
       stored into a file, This is useful for persistent data. For example, PHP sessions
       automatically save and restore object.
       There are two popular methods of serializing variables.
       serialize()
       unserialize()
  d) Write the syntax for creating Cookie.
       ANS-
       Syntax:
       setcookie(name, value, expire, path, domain, security);
  e) Write syntax of Connecting PHP Webpage with MySQL`
       ANS-
       Syntax:
       mysqli_connect($server, $username, $password, $database_name)
  f) Define GET and POST methods.
       ANS-
     The GET method is used to submit the HTML form data. This data is collected by the
     predefined $_GET variable for processing.
     the POST method is also used to submit the HTML form data. But the data submitted
     by this method is collected by the predefined superglobal variable $_POST
1|P age
  g) State the use of “$” sign in PHP.
       ANS-
       The “$” sign is used for declaring a variable in PHP.
       Example: $name= "Viji"
Q.2) Attempt any THREE of the following.                                  (12 Marks)
   a) Write a program using foreach loop.
       ANS-
       <?php
       $season = array ("Summer", "Winter", "Autumn", "Rainy");
       foreach ($season as $element) {
       echo "$element";
       echo "</br>";
       }
       ?>
   b) Explain Indexed and Associative arrays with suitable example.
       ANS-
    • Indexed array are the arrays with numeric index. These arrays can store numbers,
        Strings and any object but their index will be represented by numbers by default, the
        array index starts from 0.
       <?php
       $a=array(22,33,"sss","v");
       echo "Accessing the array elements directly:</br>";
       echo $a[2], "</br>";
       echo $a[0], "</br>";
       echo $a[1], "</br>";
       ?>
    • Associative arrays are used to store key value pairs. Associative arrays have strings
        as keys and behave more like two-column tables. The first column is the key, which
        is used to access the value.
        <?php
        $ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
        echo $ages["Clark"],"</br>";
        echo $ages["Peter"],"</br>";
        echo $ages["John"];
        ?>
   c) Define Introspection and explain it with suitable example.
       ANS-
       Introspection is the ability of a program to examine an object's characteristics, such as
       its name, parent class (if any), properties, and methods.
       With introspection, we can write code that operates on any class or object.
       <?php
       class student
       {
       }
       if(class_exists('student'))
       {
2|P age
     $ob=new student();
     echo "This is class";
     }
     else
     {
     echo "Not exist";
     }?>
  d) Differentiate between Session and Cookies.
     ANS-
3|P age
Q.3) Attempt any THREE of the following.                                  (12 Marks)
    a) Differentiate between implode and explode functions.
       ANS-
        <?php                                      <?php
        $a[0]="chocolate";                         $text="chocolate,strawberry,vanila";
        $a[1]="strawberry";                        $a=explode(",",$text);
        $a[2]="vanila";                            print_r($a);
        $text=implode(" <br>",$a);                 ?>
        echo $text;
        ?>
    b) Write a program for cloning of an object.
       ANS-
       <?php
       class clonedemo {
       public $data1;
       public $data2;
       public $data3;
       }
       $obj = new clonedemo();
       $copy = clone $obj;
       $obj->data1 = "PHP";
       $obj->data2 = "with";
       $obj->data3 = "Web";
       $copy->data1 = "develop";
       $copy->data2 = "web";
       $copy->data3 = "project";
       echo "$obj->data1 $obj->data2
       $obj->data3</br>";
4|P age
       echo "$copy->data1 $copy->data2
       $copy->data3";
       ?>
   c) Define session and explain how it works.
      ANS-
       A session is a way to store information (in variables) to be used across multiple
       pages. Sessions allow us to store data on the web server that associated with a session
       ID. Once we create a session, PHP sends a cookie that contains the session ID to the
       web browser. In the subsequent requests, the web browser sends the session ID
       cookie back to the web server so that PHP can retrieve the data based on the session
       ID and make the data available in our script.
       An alternative way to make data accessible across the various pages of an entire
       website is to use a PHP Session.
       A session creates a file in a temporary directory on the server where registered
       session variables and their values are stored. This data will be available to all pages
       on the site during that visit. The location of the temporary file is determined by a
       setting in the php.ini file called session.save_path.
   d) Write Update and Delete operations on table data.
      ANS-
      Update: Data can be updated into MySQL tables by executing SQL UPDATE
      statement through PHP function mysql_query()
      <?php
      $h="localhost:3306";
      $u="root";
      $p="";
      $db="";
      $conn=mysqli_connect($h,$u,$p,$db);
      if(!$conn)
      {
      die("fail to connect".mysqli_connect_error());
      }
      else
      echo"connected successfully</br>";
      $sql="UPDATE prod SET pname='handwash' WHERE pid=111";
      if(mysqli_query($conn,$sql))
      {
      echo"data updated";
      }
      else
      {
      echo"could not update record",mysqli_error($conn);
      }
      mysqli_close($conn);
      ?>
5|P age
       Delete: Data can be deleted into MySQL tables by executing SQL DELETE
       statement through PHP function mysql_query().
       <?php
       $host='localhost:3306';
       $user='root';
       $pass='';
       $db='product';
       $conn=mysqli_connect($host,$user,$pass,$db);
       if(!$conn)
       {
       die("fail to connect".mysqli_connect_error());
       }
       echo"connected successfully";
       echo"<br>";
       $sql="delete from prod where pid=222";
       if(mysqli_query($conn,$sql))
       echo("data deleted");
       else
       echo"could not insert record",mysqli_error($conn);
       mysqli_close($conn);
       ?>
Q.4) Attempt any THREE of the following.                                   (12 Marks)
   a) State the variable function. Explain it with example.
       ANS-
       PHP supports the concept of variable functions. This means that if a variable name
       has parentheses appended to it, PHP will look for a function with the same name as
       whatever the variable evaluates to, and will attempt to execute it.
       <?php
       function add($a,$b)
       {echo "addition =",$a+$b,"</br>";
       }
       function sub($a,$b)
       {echo "sutraction",$a-$b."</br>";}
       function fun($string)
       { echo $string;}
       $f = 'add';
       $f(2,3); // This calls add()
       $f='sub';// This calls sub()
       $f(6,3);
       $f='fun';
       $f('test'); // This calls fun()?>
       ?>
6|P age
  b) Explain the concept of Serialization with example.
     ANS-
     Serialization is a technique used by programmers to preserve their working data in a
     format that can later be restored to its previous form. Serializing of on object means
     Converting it to a byte Stream representation that can be stored in a file
     In serialization two functions can be used
     1. serialize ()
     2. unserialize ()
     1 . Serialize () :
     - The Serialize () used to Convert array into byte stream
     - It is also used to Convert object into byte stream.
     Program :
     <?php
     $a = serialize(array("Red", "Green", "Blue"));
     echo $a;
     ?>
     2. unserialize ( ) ;
     - The unserialize () used to convert byte stream into array
     - It is also used to convert byte stream into object
     Program :
     <?php
     $data = serialize(array("Cricket", "Football", "Hockey"));
     echo $data;
     echo "<br>";
     $un = unserialize($data);
     print_r($un);
     ?>
  c) Answer the following:
        i.   Get session variables
       ii.   Destroy session
     ANS-
        i.   Get session variables
     Session variables are not passed individually to each new page, instead they are
     retrieved from the session we open at the beginning of each page. All session variable
     values are stored in the global $_SESSION variable.
     Program
     <?php
     session_start();
     $_SESSION["favcolor"]="green";
     echo "Your favourite colour is ".$_SESSION["favcolor"];
     ?>
7|P age
       ii.   Destroy session
     To remove all global variables and destroy the session, session_destroy() function is
     used. It does not take any arguments and a single call can destroy the session.
     Program:
     <?php
     session_start();
     $_SESSION["favcolor"]="green";
     echo "Your favourite colour is ".$_SESSION["favcolor"];
     session_destroy();
     ?>
  d) Explain Inserting and Retrieving the query result operations.
     ANS-
     Insert data: Data can be updated into MySQL tables by executing SQL UPDATE
     statement through PHP function mysql_query().
     Program:
     <?php
     $host="localhost:3306";
     $user='root';
     $pass='';
     $db='student_data';
     $conn=mysqli_connect($host,$user,$pass,$db);
     if(!$conn)
     {
     die("fail to connect".mysqli_connect_error());
     }
     echo"connected successfully";
     $sql="insert into student1(roll,name,marks)values(1,'Ramesh',67),
     (2,'suresh',88),
     (3,'Ganesh',75),
     (4,'Rupesh',88)";
     if(mysqli_query($conn,$sql))
     {
     echo"data inserted";
     }
     else
     echo"not inserted",mysqli_error($conn);
     mysqli_close($conn);
     ?>
     Retrieve the query result: Data can be retrieved into MySQL tables by executing SQL
     SELECT statement through PHP function mysql_query().
     <?php
     $h="localhost:3306";
     $u="root";
8|P age
     $p="";
     $db="";
     $conn=mysqli_connect($h,$u,$p,$db);
     if(!$conn){
     die("Database cannot connect");
     }
     else{
     echo "Database connected<br>";
     }
     $sql='select * from sample';
     $val=mysqli_query($conn,$sql);
     if(mysqli_num_rows($val)>0){
     while($row=mysqli_fetch_assoc($val)) {
     echo "ID: {$row['ID']}<br>";
     echo "Name: {$row['Name']}<br>";
     echo "Salary: {$row['Salary']}<br>";
     }}
     else{
     echo "No results";
     }
     mysqli_close($conn);
     ?>
  e) Create a web page using GUI components.
     ANS-
     <html>
     <body>
     <form name="f1" method="post" action="">
     Enter Your Name here:<input type="text" name="name">
     <br><br>
     Enter Your Address Here:<textarea name="textarea"></textarea>
     <br><br>
     Gender:
     <input type="radio" name="m">Male
     <input type="radio" name="f">Female
     <br><br>
     Hobbies:
     <input type="checkbox" name="check"> Dancing
     <input type="checkbox" name="check"> Playing
     <input type="checkbox" name="check"> Singing
     <br>
     <td>
     <label>Course</label>
     </td>
     <td>
     <select name="course">
9|P age
<option>IF6I</option>
<option>C06I</option>
<option>ME6I</option>
<option>CE6I</option>
</select>
</td>
<br>
<input type="submit" name="Submit ">
</form>
</body>
</html>
Q.5) Attempt any TWO of the following.                                      (12 Marks)
   a) Explain any three data types used in PHP.
       ANS-
       Data types are used to hold different types of data or value. PHP supports 8 primitive
       data type that can be divide into 3 types.
       1. Scalar Type:
           i.  Integer: This data type only holds numeric value. Hols only whole number
               including positive any negative numbers.
          ii. Float: This data type holds floating point numbers or represents numeric value
               with decimal points
        iii. String: A string is a sequence of characters. A string is declared using single
               quote or double quote.
         iv.   Boolean: Boolean data type represents Boolean true (1) or false (0).
       2. Compound data type:
           i.  Array: An array stores multiple value in a single variable and each value is
              identified by position.
          ii. Object: Object are defined as instance of user defined class that can be hold
               both value and functions.
       3. Special data type:
           i.  Resource: The Resource data type is not actual data type. It stores reference to
               function.
          ii. Null: Null is a special data type which can have only one value NULL.
   b) Write a program to connect PHP with MySQL.
       ANS-
       Program:
       <?php
       $host="localhost";
       $user="root";
       $pass="";
       $conn=mysqli_connect($host,$user,$pass);
       if(!$conn){
       die("Could Not Connect database");
       }
       else{
10 | P a g e
       echo "Database Connected";
       }
       mysqli_close($conn);
       ?>
    c) Explain the concept of overriding in detail.
       ANS-
       In function overriding, both parent and child classes should have same function name
       with and number of arguments. It is used to replace parent method in child class. The
       purpose of overriding is to change the behavior of parent class method. The two
       methods with the same name and same parameter is called overriding.
       <?php
       class p
       {
       function dis1()
       {
       echo "This is parent class<br>";
       }
       }
       class child extends p
       {
        function dis1()
        {
        echo "This is child class";
        }}
       $p=new p();
       $p->dis1();
       $c=new child();
       $c->dis1();
       ?>
Q.6) Attempt any TWO of the following.                                        (12 Marks)
   a) Explain web page validation with example.
       ANS-
       Validation means check the input submitted by the user. There are two types of
       validation are available in PHP.
       1. Client-side validation: Validation is performed on the client machine web
       browsers.
       2. Server-Side Validation: After submitted by data, The data has sent to a server and
       perform validation checks in server machine.
       Program:
       <html>
       <body>
       <?php
       $name = $email = $gen = $add = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["name"])) {
11 | P a g e
        $name = "Name is required";
        }
        if (empty($_POST["email"])) {
        $email = "Email is required";
        }
        if (empty($_POST["addr"])) {
        $add="Address is required";
        }
        if (empty($_POST["gender"])) {
        $gen = "<br>Gender is required";
        }
        }
       ?>
       <form name="f1" method="post" action="">
       Enter Your Name here:<input type="text" name="name">
       <?php echo $name;?>
       <br><br>
       Enter Your Address Here:<textarea name="addr"></textarea>
       <?php echo $add;?>
       <br><br>
       Enter Your E-mail here:<input type="email" name="email">
       <?php echo $email;?>
       <br><br>
       Gender:
       <input type="radio" name="gender">Male
       <input type="radio" name="gender">Female
       <?php echo $gen;?>
       <br><br>
       <input type="submit" name="Submit ">
       </form>
       </body></html>
    b) Write a program to create PDF document in PHP.
       ANS-
       <?php
       require('fpdf.php');
       $pd = new FPDF();
       $pd->addpage();
       $pd->setfont("Arial", "B", 20);
       $pd->cell(80,10,"PHP PROGRAMMING",1);
       $pd->output("Myfile.pdf", "I");
       ?>
    c) Elaborate the following:
          i.   __call()
         ii.   mysqli_connect()
       ANS-
12 | P a g e
           i.   __call()
                The – call() method is invoked automatically when a non- existing method or
                inaccessible method is called
                Syntax :
                public function --call ( $name. $arguments)
                {
                   // body of -- call ( )
                }
                Here. It has two arguments,
                $name - name of the method being called by object
                $arguments - array of arguments passed to method call.
                - In PHP , function overriding is done with the help of magic function -_call ()
          ii.   mysqli_connect()
                The mysqli_connect() function is used to connect with MySQL database. It
                returns
                resource if connection is established or not.
                Syntax:
                mysqli_connect(server, username, password, database_name)
                Program:
                <?php
                $host="localhost";
                $user="root";
                $pass="";
                $conn=mysqli_connect($host,$user,$pass);
                if(!$conn){
                die("Could Not Connect database");
                }
                else{
                echo "Database Connected";
                }
                mysqli_close($conn);
                ?>
13 | P a g e