Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

List any four advantages of PHP ?

Platform Independent: The PHP based developed web applications can be easily run on
any platform.
Simple and Easy: PHP is simple and easy to learn and code. The command functions of
PHP can easily learn and understood. The syntax is simple and flexible to use.
Database: It has a built-in module that is used to connect to the database easily.
Multiple databases can be integrated with PHP.
Fast: PHP is known as the fastest Programming language as compared to another.

State the features of PHP.


- Web Application Features
- CLI (Command Line Interface)
- Built-in Modules
- Object-Oriented Programming (OOP)
- Pre-Compilation
- Real Time Access Monitoring
- File I/O

List various data types in PHP with example.


- Data types are used to hold different types of data or values.
- Scalar type
i. Integer [example: decimal octal hexadecimal values]
ii. Float [example:3.14, -5.5]
iii. String [example: ’Shrinidhi’]
iv. Boolean [example: True or False] $a=true
- Compound Type
i. Array [example: variable_name = array (element 1, element two)]
ii. Object [example:]
- Special Type
i. Resource [example: string of reference to functions]
ii. Null [example: variable that has no value. $x+ null;]

State the use of "$" sign in PHP.


- Variables in PHP are represented by a dollar sign ($) followed by the name of the
variable. Example: $name.
For Loop For-Each Loop
For statement is used when you know how foreach loop is used for array and objects
many times you want to execute a
statement or a block of statements
The iteration is clearly visible. The iteration is hidden.
Good performance. Better performance.
The stop condition is specified easily. The stop condition must be explicitly
specified.

Compare For loop and foR

State use of str_word_count along with its syntax.


The str_word_count() function is a string function used to count the number of words in
a specified string. Syntax: str_word_count(string)

Define Serialization.
• 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 an object means converting it to a byte stream representation that can be


stored in a file.

• Serialization in PHP is mostly automatic, it requires little extra work from the
programmer, beyond calling the serialize() and unserialize() functions.

Write Syntax for Creating Cookie.


We use the setcookie() function to create a cookie. Syntax:
setcookie(name, value, expire, path, domain, secure, HttpOnly);

Write Syntax for Connecting PHP Webpage with MySQL.

We use the mysqli_connect() function to connect to the database. Syntax:


mysqli_connect($servername, $username, $password, $database);
State the use of “$” sign in PHP.
Variables in PHP are represented by a dollar sign ($) followed by the name of the
variable. Example: $name.

6. Define GET and Post Methods.


GET Method:
• This is the built in PHP super global array variable that is used to get values submitted
via HTTP GET method.

• Data in GET method is sent as URL parameters that are usually strings of name and
value pairs separated by ampersands (&).

• URL with GET data look like this : http://www.abc.com/dataread.php?


name=ram&age=20.

POST Method:
• • This is the built in PHP super global array variable that is used to get values
submitted via HTTP POST method.

• • Data in POST method is sent to the server in a form of a package in a separate


communication with the processing script.

• • User entered Information is never visible in the URL query string as it is visible
in GET.

State the use of “$” sign in PHP.


Variables in PHP are represented by a dollar sign ($) followed by the name of the
variable. Example: $name.

List introspection methods


- class_exists()-Checks whether a class has been defined.
- interface_exists()-Checks whether the interface is defined.
- method_exists()-Checks whether an object defines a method.
- get_class()-Returns the class name of an object.
Write a program using foreach loop.
<?php
//declare array
$employee = array (
"Name" => "Anurag",
"Email" => "anurag.sawant@vpt.edu.in",
"Age" => 18,
"Gender" => "Male"
);
//display associative array element through foreach loop
foreach ($employee as $key => $element) {
echo $key . " : " . $element;
echo "</br>";
}
?>

OUTPUT:-
Name : Anurag
Email : anurag.sawant@vpt.edu.in
Age : 18
Gender : Male

Define session and explain how it works.

A session is a way to store information (in variables) to be used across multiple pages.

• Unlike a cookie, the information is not stored on the user’s computer.

• Session data is stored on the server side and each Session is assigned with a unique
Session ID (SID) for that session data.

• As session data is stored on the server there is no need to send any data along with
the URL for each request to server.

• More data can be stored in session as compared with cookie because location for
storing data is a server.

• PHP stores the session data in a temporary file on the server, the location of the
temporary file is specified by the session.save_path directives in the PHP configuration
file
2. Explain Indexed and Associative Array with suitable examples.
Indexed Array :
• An array with a numeric index where values are stored linearly.
• Numeric arrays use number as access keys.
• An access key is a reference to a memory slot in an array variable.
• The access key is used whenever we want to read or assign a new value an
array element
• Example:

<?php
$name[0]="Anurag";
$name[1]="Karan";
$name[2]="Justin";
echo "Size: $name[0], $name[1] and $name[2]";
?>
OUTPUT:- Names: Anurag, Karan and Justin

Associative Array
• This type of arrays is similar to the indexed arrays but instead of linear
storage, every value can be assigned with a user-defined key of string type.
• An array with a string index where instead of linear storage, each value
can be assigned a specific key.
• Associative array differs from numeric array in the sense that associative
arrays use descriptive names for id keys.
<?php
$salary=array("Justin"=>"99999999","Anurag"=>"250000","Karan"=>"50");
echo "Justin salary: ".$salary["Justin"]."<br/>";
echo "Anurag salary: ".$salary["Anurag"]."<br/>";
echo "Karan salary: ".$salary["Karan"]."<br/>";
?>
OUTPUT:- Justin salary: 99999999 Anurag salary: 250000 Karan salary: 50
Define Introspection with suitable example.

• Introspection in PHP offers the useful ability to examine an object's characteristics, such as its name,
parent class (if any) properties, classes, interfaces and methods.

• PHP offers a large number functions that you can use to accomplish the task.

• They are: o class_exists()

o get_class()

o get_parent_class()

o is_subclass_of()

o get_declared_classes()

o get_class_methods()

o get_class_vars()

o interface_exists()

o method_exists()

<?php

if (class_exists('Demo'))

$demo = new Demo();

echo "This is Demo class.";

else

echo "Class does not exist";

?>

OUTPUT:- Class does not exist


Write Update and Delete Operations on table data.
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = "myDB";
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die('Could not Connect MySQL Server:' . mysqli_connect_error());
}
// For Inserting Data in the Table
$firstname = 'Anurag';
$lastname = 'Sawant';
$mobile = '9324059612';
$sql = "INSERT INTO users (firstname,lastname,mobile)
VALUES ('$name','$email','$mobile')";
if (mysqli_query($conn, $sql)) {
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . mysqli_error($conn);
}
mysqli_close($conn);
// For Deleting Data from the Table
$sql = "DELETE FROM users WHERE firstname='Anurag";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
OUTPUT:- New record has been added successfully !
Record deleted successfully.
1. State the variable function. Explain it with example.
• 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.
• Among other things, this can be used to implement call-backs, function tables
and so forth.
• Variable functions won't work with language constructs such as echo, print,
unset(), isset(), empty(), include, require and the like.
• We utilize wrapper functions to make use of any of these constructs as variable
functions.
<?php
function simple()
{
echo "In simple()<br />\n";
}
function data($arg = '')
{
echo "In data(); argument was '$arg'.<br />\n";
}
$func = 'simple';
$func(); // This calls simple()
$func = 'data';
$func('test'); // This calls data()
?>
OUTPUT:- In simple() In data(); argument was 'test'.
1. How can access the data sent through URL with GET method?
- The data sent by GET method can be accessed using QUERY_STRING environment
variable.
- The PHP provides $_GET associative array to access all the sent information using
GET method.
- Syntax: print_r($_GET);

2. List the attributes of Cookies.


- Name -The unique name is given to a particular cookie.
- Value - The value of the cookie.
- Expires - The time when a cookie will get expire.
- Path- The path where browser to send the cookies back to the server
Explain Concept of Serialization with example
• Serialization is a technique used by programmers to preserve their working data
in a format that can later be restored to its previous form.
• A serialize data means a sequence of bits so that it can be stored in a file, a
memory buffer or transmitted across a network connection link.
• It is useful for storing or passing PHP values around without losing their type
and structure.
• Serialize() : The serialize() converts a storable representation of a value.
• The serialize() function accepts a single parameter which is the data we want to
serialize and returns a serialized string.
SYNTAX:- serialize(value);

unserialize() : unserialize() can use string to recreate the original variable values
i.e., converts actual data from serialized data.
Syntax : unserialize(string);

Example:
<?php
$s_data= serialize(array('Welcome', 'to', 'PHP'));
print_r($s_data . "<br>");
$us_data=unserialize($s_data);
print_r($us_data);
?>
OUTPUT:

a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";} Array ( [0] => Welcome [1] => to


[2] => PHP )

Explain self-processing forms in PHP with example.


- PHP_SELF is a variable that returns the current script being executed. This variable
returns the name and path of the current file (from the root folder). You can use this
variable in the action field of the FORM. the $_SERVER["PHP_SELF"] sends the submitted
form data to the page itself, instead of jumping to a different page. This way, the user
will get error messages on the same page as the form.
Answer the following:
i) Get Session Variables ii) Destroy Session
Get Session Variables.
• Session variable can be read with a help of a PHP global variable: $_SESSION.

• While accessing the data using $_SESSION variable we have to mention key in the
$_SESSION variable.

• For example, we want retrieve the data stored in session variable.

<?php
session_start();
$_SESSION['name'] = "Anurag Sawant";
echo "Name : " . $_SESSION["name"];
?>
OUTPUT:- Name : Anurag Sawant

Destroy Session.
• Session automatically gets destroyed when user quits browser.

• If someone wants to destroy the session after certain operation example after a logout
that can be done using inbuilt PHP functions.

• A PHP function session_unset() is used to remove all session variables and


session_destroy() is used to destroy session.

• Example:
<?php
session_start();
$_SESSION['name'] = "Anurag Sawant";
echo "Name : " . $_SESSION["name"];
session_unset(); // remove all session variables
session_destroy(); // destroy the session
echo "Name : " . $_SESSION["name"]; // Will throw an error
?>
OUTPUT:-
Name : Anurag Sawant Notice: Undefined index: name in D:\xampp\htdocs\archives\
test.php on line 9
Name :
5. Create a Web Page using GUI Components

<html>
<head>
<title>Web Page using GUI Components</title>
</head>
<body>
<form method="get" action="">
<label for="fName">First Name</label><br>
<input name="fName" type="text"><br>
<label for="lName">Last Name</label><br>
<input name="lName" type="text"><br>
<label for="phone">Phone Number</label><br>
<input name="phone" type="number"><br>
<label for="email">Email</label><br>
<input name="email" type="email"><br>
<label for="gender">Select Your Gender</label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender"
value="female">Female
<br>
<label for="class">Select Your Class</label>
<select name="class">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explain any three datatypes used in PHP
Integer
• This data type holds only numeric values.

• Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point.

• The range of integer values are -2,147,483,648 to +2,147,483,647.


String:
• A string is a sequence of characters.

• A string are declares using single quotes or double quotes.

• Syntax: $variableName = "Value of String";

Example: “Hello PHP”, ‘Hello PHP’;

Boolean
• • The Boolean data types represents two values, true(1) or false(0).

• • Syntax
$variableName = True/False ;
EXAMPLE: $a=True;
$b=False;

State the variable function. Explain it with example


- 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.
- Among other things, this can be used to implement call-backs, function tables and so
forth.
- Variable functions won't work with language constructs such as echo, print, unset(),
isset(), empty(), include, require and the like.
We utilize wrapper functions to make use of any of these constructs as variable
functions.

State the use of str word_count along with its syntax.


The str_word_count() function is a string function used to count the number of words in
a specified string.
Syntax: str_word_count(string)
Write a Program to connect PHP with MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username,
$password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname,
email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

OUTPUT:
New record created successfully
3. Elaborate the Following:
i) __call() ii) mysqli_connect()
__call()
• In PHP function overloading is done with the help of magic function __call().

• Function overloading is a feature of object-oriented programming that allows to create more


than one method with the same name but different number of arguments/parameters.

• Overloading in PHP creates properties and methods dynamically.

• Function overloading contains same function name and that function performs different task
according to number of arguments.

• For example, find the area of certain shapes where radius is given then it should return area
of circle if height and width are given then it should give area of rectangle and others.

• The __call() method accepts two arguments:

• $name is the name of the method that is being called by the object.

• $arguments is an array of arguments passed to the method call.

• Syntax:

public __call ( string $name , array $arguments )


mysqli_connect()
• The mysqli_connect() function in PHP is used to connect you to the database.

• Syntax:

mysqli_connect ( "host", "username", "password", "database_name" )


• WHERE

host
It is optional and it specify the host name or IP address. In case of local server localhost is used
as a general keyword to connect local server and run the program.
username
It is optional and it specify MySQL username. In local server username is root.
password
It is optional and it specify MySQL password.
database_name
It is database name where operation perform on data. It also optional.
• Return values:

It returns an object which represent MySQL connection. If connection failed then it


returns FALSE.

You might also like