php Questions and Answers for Exams set B
PHP
Constants:- A
constant is an identifier (name) for a simple value. The value cannot be
changed during the script. A valid constant name stars with a latter or underscore
(no $ sign before the constant name).
Unlike variables constants are automatically global
across the entire script.
To create a constant use the define () function.
Syntax:-
define(name,value,case-insensitive).
Parameters:-
name:-specifies the name of the constant.
Value:- specifies the
value of the constant.
Case-insensitive:- specifies
whether the constant name should be case
in-sensitive.
Default is false.
Variables
in PHP:-Variable are used to store data, like
string of text, numbers etc. variable
values can change over the course of a script. Some important things to know
about variables are:-
·
In PHP, a variable doesn’t need to be
declared before adding a value to it. PHP automatically converts the variable
to the correct data type, depending on its value.
·
After declaring a variable it can be
reused throughout the code.
·
The assignment operator (=) used to
assign value to a variable.
In PHP variable can be declared as:- $
var_name=value;
Naming
conventions for PHP variables:-
·
Variable names are case-sensitive.
·
All variables in PHP start with a ($)
sign, followed by the name of the variable.
·
A variable name must start with a letter
or the underscore character(_).
·
A variable name cannot star with a
number.
·
A variable name in PHP can only contain
alphanumeric characters and underscores (A-Z, 0-9, and (_)).
·
A variable name cannot contain spaces.
How we
can write a PHP statement?
Ans.
A
PHP script can be placed anywhere in the document.
A PHP script start with <?php and ends with ?>.
<?php
//php
code goes here
?>
The default file extension for php files is “.php”.
A php file normally contain HTML tags and some php scripting code.
Example:-
<?php
Echo “Hello
Friends”;
?>
Output:-
Hello Friends
Comments
in PHP:-A comment in php code is a line that is
not read/execute as part of the program. Its only purpose is to read by someone
who is looking at the code.
PHP supports:-
·
Single line comment(//,#).
·
Multiple line comment (/* */).
PHP
case sensitivity:- In PHP, all keywords. (e.g.:- If,
else, While, echo) classes, functions, and userdefined function are not
case-sensitive.
E.g.:-
echo
But the variable names are case-sensitive in php.
E.g:-($
COLOR and $ color are the two different
variable names).
How can we create and modify table in my SQL?
Ans.Create
a table
Syntax:-
create table tablename
( Column namedatatype(size);
(Column datatype(size);
)
Eg:-
Create table student
(
Sid int(11),
Sname varchar2(30),
Strade varchar2(30));
Modify
a table in Mysql:-
Alter table table_name
Modify column column_name datatype
Discuss the relationship between php and
mysql?
Ans.
Mysql is the database system where you can create tables and store data on
server.
Php is
server-side scripting language used to develop website and mainly used for
manipulation data . It is
widely used to store and retrieve data from
Mysql database which resides on
the server .A powerful tool for making
dynamic and interactive web pages.
What
is the use of do-while loop? Give example?
Ans.
The
do-while loop will always execute the block of code once, it will then check
the condition and repeat the loop while the specification condition is true.
Syntax:-
Do
{
//Code to be executed;
}While (condition is true);
Eg:- <?php
X=1;
Do
{
Echo”The number is :$x”.”<br>”;
$x++;
}While($x<=3);
?>
In do while
loop the condition is tested after execution the statement within the loop.
This means that the do while loop would execute its statement at least once,
even the first time.
Eg:-<?php
$a=6;
Do
{
Echo”The number is:$a”.”<br>”;
$a++;
}While ($a<=5);
?>
The do-while would executes its statement at least once,
even if the condition fails for the first time itself.
Write
down the various steps to create function in php?
Ans.
In
all programming and scripting languages,
A function is a block of statements that can be used
repeatedly in a program. In php the concept of the function is the same as in
another language like ’C’. There are more than 1000 in-built function into the
standard php distribution besides these we can define function as per our requirements
These are called ’user define function’
Syntax:-
function function_name()
{
Statement 1:
Statement 2:
Statement 3:
}
Elements of a function:-
Function:-A function declaration starts with the
special word ‘function’.
Name of the function:-The function name is define by
the user.A valid function name start with a letter or underscore, followed by
any number of letter, number or underscores.
Remember that function names are case-insensitive.
Opening
and closing curly braces({}):-The function body enclosed
within a pair of braces which may contain variables name an actual function code.
The opening curly brace({) indicate beginning of function code and closing
curly brace (}) indicates the termination of the function.
Eg:-<?php
Function myfunction()
{
Echo”good morning”;
}
Myfunction();
?>
Explain php mail.
Ans.Php mail() function code to send
emails from a form. you can use a php mail () function to send an email with php.
The simplest way to do this is to send a
text email. This is one way to handle sending
you the result user when a visitor to your website fills out a form.
Example:- send a simple email-
<?php
//the
message
$msg=”first
line of text \n second line of text “;
//use
word warp() if lines are longer than 70 characters.
$msg=wordwrap($msg,70);
//send
email
?>
DEFINITION AND USAGE:- The mail() function allows you
to send emails directly from a script
SYNTAX:- Mail(to,subject,message,headers,parameters);
PARAMETERS
DESCRIPTION
* To
Required specifies the
receiver/receivers of the email.
*subject
Required specify the subject of the
Emails.
NOTE:-this parameter can not
contain any new line character
*message
Required,
define the message to be
Sent. each line should be separated
With
a LF(\n).
Line should be exceed 70 characters.
WINDOWS NOTE:-if a full stop is
Found on the beginning of a file
In the message, it might be removed
The full stop with a double dot:
<?php
$txt=str_replace(“\n.”,”\n.”,$txt);
?>
*headers
optional. Specify the additional headers
Like from , cc and bcc the additional
Headers should be
seprated with CRLF
(\H\n) optional.
*parameter
optional Specifies an additional
Parameter to the. Send mail program
(the
one defined in the sendmail_path
Configuration setting).
Write a
program to print “Good morning” in php?
ANS:-<?php
Echo”good morning”;
?>
Output:-
Good morning.
Explain get and post method with example?
Ans-There are two ways the browser client
can send information to the web sever.
·
The
get method
·
The
post method
·
The Get method:- The get method sends the
encoded user information appended to the page request. The page and the encoded
information are separated by the ? charter.
Eg:-
//www.test.com/index.html?name=value/&name2=value2.
·
The
get method produce a long string that appear in your server logs, in the
browser locatin:box.
·
The
get method is restricted to send upto 1024 character only.
·
Never
use get method if you have password or other sensitive information to be send
to the sever.
·
The
data send by get method can be accessed using query_string environmental
variable.
·
The
php provides $_get associated array to access all the send information using
get methed.
Eg:-
<?php
If($_get[“name” ]||$_get(“age”))
{
Echo”welcome”.$_get[‘name’]”<br>”;
Echo”you
are”.$_get[‘age’].”years old”;
Exit();
}
<html>
<body>
<form
action=”<?php $_php_self?>”
Method=”get”>
Name:<input
type=”text” name=”name”/>
Age:<input
type=”submit”/>
</form>
</body>
</html>
The Post Method:-
The post method
transfers information via HTTP headers. The information is encoded as described
in case of GET method and put into a header called QUERY_STRING.
·
The
POST Method does not have any
restriction ondata size to be sent
·
The
POST method canbe used to send ASCII as well
as binary data
·
The
data sent by POST method goes through HTTP Header so security depends on HTTP
protocol by using secure HTTP you can make sure the your information is secure
·
The
PHP provides $_POST associated array to access all the sent information using
POST method
Eg:- <?php
If($_POST["NAME”]||$_POST[”AGE”)
{
IF(preg_match(“/[^a-Za-Z’-]/”;
$_POST[‘NAME’]))
{
DIE(“invalid name and
name should be alpha”);
}
Echo”welcome”.$_POST[‘NAME’].”<BR>”;
Echo”you
are”.$_POST[‘AGE’].”YEAR OLD”;
Exir();
}
?>
<HTML>
<BODY>
<FORM
ACTION=”</PHP$_PHP_SELE?>”METHOD=”POST”>
Name:<input
type=”text”name=”name”/>
Age:<input
type=”text”name=”age”/>
<input
type=”submit”/>
</form>
</body>
</html>
What
are the various data types used in php?
Php
data types
Variable can store data of
different types and different data types can do different things. php supports
the following data types:-
·
String
·
Integer
·
Float(floating
point numbers also called double)
·
Boolean
·
Array
·
Object
·
Null
·
Resource
Php
string:- A string
is a sequence of characters like ”HELLO WORLD”
A string can be any
text inside quotes you can use single or double quotes
Eg:-
<?php
$X=”HELLO WORLD!”;
$Y=’HELLO WORLD!’;
Echo $x;
Echo “<br>”;
Echo $y;
?>
O/P hello world !
Hello world !
Php integer->an integer database is a non
–decimal number between -2,147,483,648 and 2,147,483,647.
Rules for
integers:-
* An integer must have at least one digit.
* An integer must not have a decimal
point.
* An integer can be either positive or
negative.
* Integer can be specified in three
formats:-
Decimal(10-based),hexadecimal(16-based-prefixed
with ox)
Or octal(8-based-prefixed
0).
Eg:-<?php
$x=5948;
Var_dump($x);
?>
o/p:- int(5948)
php float:-a float (floating point number)
is a number with a decimal point or a number is exponential form.
Eg:- <?php
$x=10.364;
Var_dump($x);
?>
o/p:- float(10.364)
php Boolean:- A Boolean represents two possible states:
true or false.
$x=true;
$y=false;
Boolean are often
used in conditional testing.
Php array :- an array stores multiple values in one single
variable .
Eg:- <?php
$cars=array(“Volvo”, “bmw”,
“Toyota”, “creta”, “alto”);
Var_dump ($cars);
?>
o/p:- array(5) {[0]=>string(5)”volvo”
[1]=>string(3) “bmw” [2]=> string(6) “toyoto” [3]=> string(5)”creta”
[4]=>string(4) “alto”}.
Php object:-an object is a data type which
stores data and information on how to
process that data .
In php, an object
must be explicitly declared ,first we
must declare a class of object for this, we
use the class keyword. a class is a structure that can contain
properties and method .
Eg:- <?php
Class car
{
Function car()
{
$this->
model=”vw”;
}
}
//create an
object
$herbie = new car();
//show object
properties
Echo $herbie->
model;
?>
o/p:- vw
php null value:- null is a special data_type which
can have only one value: null.
A variable of data_type
null ia a variable that has no value assign to it.
Tip:- if a variable is created without a value ,it
is automatically assigned a value of null , variable can also be empted by
setting a value to null.
Eg:- <?php
$x=”hello world!”;
$x=null;
Var_dump($x);
?>
o/p:- null
php resources->
the special resource type is not an actual data type .it is the storing
of a reference to functions and resources external to php.a common example of using the
resource data type is data base call.
Explain break and
continue statement with example ?
Ans:- break and continue statements
Break statement :-
For
($i=0;$i<=10;$i++)
{
If($i==7)
{
Break;
}
}
Continue statement :-
For($i=0;$i<=10;$i++)
{
If($i==7)
{
Continue;
} }
Break statement
In php break keyword helps to terminate
looping in php programming. When a loop
faces break keyword in its body, it terminate its execution immediately. So, be
careful to use break keyword inside a php conditional statement otherwise the
loop body will execute no more.
Eg:-
<?php
For($i=0;$i<10;$i++)
{
If ($i==5)
{
Break;
}
Echo
$i.’ ’;
?>
o/p:- 0 1 2 3 4
from the above
program you can see that for loop body is executing only five times although it
has been declared to execute ten times.
Continue statement
The continue
statement start a new loop without executing current loop body. When a loop
finds continue keyword in its body, it stops the body execution and restarts
the loop. So, be careful to use the continue keyword inside a conditional
statement otherwise loop body will not be executed.
Eg:-
<?php
For($i=0;$<10;$i++)
{
If($i==5)
{
Continue;
}
Echo
$i.’ ’;
}
?>
o/p:-0 1 2 3 4 5 6 7
8 9
In this eg, when
variable $i=5,the continue statement is
executed. so, the execution of
Loop
body is ignored and 5 is not printed with echo function.
write
a program to find out maximum out of 3 number?
Ans: >?php
$a=5;
$b=15;
if($a>$b&&$a>$c)
{
echo “a is greater”;
}
elseif($b>$a&&$b>$c)
{
Echo “b is greater”;
}
else
{
echo”c is greater”;
}
?>
Output:- c is greater
Why
PHP is called a scripting language?
Ans. Scripting Languages, which can be
embedded within HTML, commonly are used to add functionality to a webpage, such
as different menu style or graphic display or to serve dynamic advertisements.
These types of languages are client-side scripting languages, affecting the data
that the end user sees in browser’s window. Other scripting languages are
server-side scripting languages that manipulate the data usually in a database
on the server. Like PHP.
PHP is a scripting language (It
uses an Interpreter) which is mostly run on a server. As JavaScript is also a
scripting language but it mostly run on a client. In PHP, we can embed PHP code
into HTML. That’s why called scripting language. If code of programming
language can embed with other language or integrate with other language or
script called scripting language. PHP is a server-side language because PHP
requires server to run a code. Code of PHP gets executed on server and result
of execution each return to the browser. That’s why PHP is called scripting
language and server-side language.
Explain scope of variable in PHP.
Ans. In PHP variable can be declared
anywhere in the script. The scope of a variable is the part of the script
whereas the variables can be referenced/used.
PHP has three different variable
scope:-
·
Local
·
Global
·
Static
Global and Local Scope: A
variable declared outside a function has a global scope and can only be
accessed outside a function.
Eg:-
<?php
$x
= 5; //Global Scope
Function
mytest(){
Echo
“<p>Variable x inside function is: $x</p>”;
}
mytest();
echo
“<p>Variable x outside function is : $x</p>”;
?>
Output:
Variable x inside
function is:
Variable x outside
function is: 5
A variable declared
within a function has a local scope and can only be accessed within that
function.
Eg.-
<?php
Function
mytest(){
$x
= 5; //Local Scope
Echo
“<p>Variable x inside function is: $x </p>”;
}
mytest();
echo
“<p>Variable x outside function is : $x</p>”;
?>
Output:
Variable x inside
function is: 5
Variable x outside
function is:
You can have local
variables with the same name in different function, because local variable are
only recognized by the function in which they are declared.
PHP the Global Keyword: The
global keyword is used to access a global variable from within the function. To
do this, use the global keyword before the variables (inside the function).
$x =
5; $x = 5;
$y =
10; $y = 10;
function
myTest(){ function myTest(){
global $x, $y; $GLOBAL[‘y’]
= $GLOBAL[‘x’] +
$y
= $x + $y; $GLOBAL[‘y’];
} }
myTest(); myTest();
echo
$y; //Output = 15 echo $y; //Output is 15
?> ?>
Output: 15 Output:
15
Actually, PHP also store all
global variables in an array called $GLOBAL[index]. The index holds the name of
the variable. This array is also accessible from within function and can be
used to update global variables directly.
PHP the static keyword:
Normally, when a function is completed/executed, all of its variables are
deleted. However sometimes we want a local variable not to be deleted we need
it for a further job. To do this, use the static keyword when you first declare
the variable:
Eg:-
<?php
Function myTest(){
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Output: 0
1
2
Then, each
time the function is called, that variable will still have the information it
contained from the last time function was called.
Note: The variable is still local to the
function.
Explain while loop in PHP.
Ans. The while loop executes a block of
code as long as the specified condition is true.
Syntax: while(
condition ){
Code
to be executed;
}
The example given below first
sets a variable $x to 1 ($x = 1). Then, the while loop will continue to run as
long as $x is less than, or equals to 5 ($x <= 5). $x will increase by 1 ech
time the loop runs ( $x++ ).
Eg:- <?php
$x
= 1;
while(
$x <= 5 ){
echo
“The number is: $x <br>”;
$x++;
}
Output: The
number is: 1
The
number is: 2
The
number is: 3
The
number is: 4
The
number is: 5
Difference between echo and print statement.
Ans.
Echo Statement
|
Print Statement
|
·
Echo
can take more than one parameter when used without parentheses.
The
syntax is:
echo
expression[,expression[,expression]…]
Note: echo($arg1,$arg2) is invalid.
·
Echo
doesn’t return any value.
·
Syntax:
void echo(string$arg1[,string$...])
·
In
PHP, echo is not a function but a language construct.
·
Echo
can take several arguments.
Eg:-
echo “Don’t”.” “.”Panic”.”!”;
//This
is valid.
·
Echo
is marginally faster.
|
·
Print
only takes one parameter.
·
Print
always returns 1 (integer).
·
Syntax:
int print(strng$arg)
·
In
PHP, print is not really a function but a language construct. However it
behaves like a function in that it returns a value.
·
Print
can’t take several arguments.
Eg:-
print “The”.”Answer”.”is”.”42.”;
//This
is invalid.
·
Print
is slower than echo.
|
Key Difference: An echo and print
function is a language construct in PHP language. An ‘echo’ gives an output in
one or more strings, while a print gives the output only in one string.
Write
a program to print addition of two numbers in PHP.
Ans.
<?php
$a
= 10;
$b
= 10;
$c
= $a + $b;
Echo
“The sum or $a and $b is $c.”;
?>
Output: The sum of 10 and 10 is 20.
Ques 20: what are the multidimensional array?
ans: a multidimensional php array is nothing more than an array in which
each array element is itself an array. A multidimensional array can, therefore,
be thought of as a table where each element is the parent array represents a
row of the table and the elements of each child array represent the columns of
the row.
The following PHP scripts provide an example of multidimensional array
where the book array is assigned an array for each element containing title and
another information of each book:
<?php
$books=array();s
$books[0]=array('title'=>'javascript in 24hr','author'=>'moncur');
$books[1]=array('title'=>'javascript unleashed','author'=>'wyke');
$books[2]=array('title'=>'network +second
edition','author'=>'harwood');
?>
what is anonymous function?explain.
Ans: php also allows generating of anonymous function, called lambda functions.
these function doesn't have name. they are assigned directly to variables and
called by the variable name. this allows the creation of transient functions
without warring about having to give them a new function name, each time they
are created.
Use create_function() to create an anonymous function. it takes two strings
as arguments. one represents the parameters list of the function, exactly as it
would appear between the parentheses in a normal function definition. the other
is a string, which contain the actual body of the functions. this technique is
best used with start function.
EXAMPLE:
$multiply=create_function('$a,$b',return $a*$b);
$result=$multiply($x,$y);
Anonymous functions do have names,but they are randomly generated strings, which
minimizes the chance of the create_function() accidently producing two
functions with the same name.
How can we create functions in php?
Ans: functions are an important tool
in any programming language. functions are code snippets that accepts values
and produce results, although there are same function that don't need to be
supplied which values to produce a result. functions are used in situation
where the same code snipped is repeated across script. the block of code held
by function is not immediately executed, but is called by a script and when it
must be executed.
while creating a function, a unique function name follows the function
keyword. A pair of opening and closing parenthesis follows the function name.
if arguments were to be accepted, the variables acting as the function's
parameter holders must be mentioned with in the parenthesis. the actual
function code, called the function's signature, which follows in enclosed
within the curly braces.
the above function simply print the text in a browser. it can be called
just like a regular php function from within any HTML page:
<html>
<body>
<?php
/*defining the function hi*/
function hi()
{
print("hi student !How are you.");
}
/*calling the function defined above*/
hi();
?>
</body>
</html>
Explain
the use of WHERE clauses?
Ans: SQL SELECT command is used to
fetch data from My sql table. we can use a conditional clause called WHERE
clause to filter our results. using WHERE clause we can specify a selection criteria
to select required records from a table.
syntax-Here is generic SQL syntax of SELECT command with WHERE clause to
fetch data from SQL table.select field 1,field 2,field n table name1,table
name2[where condition 1[AND[OR]] condition2...]
·
you can use one or more tables separated by comma to include various
condition using a WHERE clause. but WHERE clause is a optional part of SELECT
command.
·
you can specify any condition using WHERE clause
·
you can specify one or more condition using AND or OR operators
·
A WHERE clause can be used along with DELETE or UPDATE SQL command also to
specify a condition.
·
The WHERE clause works like a if condition in any programming language.this
clause is used to compare a given value with the field value available in my
sql table.if given value from outside is equal to the available field value in
My SQL table then it returns that row.
How php
string variable is used?
Ans: String:- string are va sequence of character that are always
internally null terminated. String variable hold character. usually a set of character
such as "S" "IVAN". string can be short or as long
desired.There is no limit to sizeit must be enclosed in quotes. either single
quotes or double can be used. there is a vital difference b/w the two types of
quote
<?php
$FirstName='abhi';
$ wer="Hello Everyone My firstname is $FirstName";
echo $wer;
?>
Double quotes are also used for expending other special character, such as
the new line character
(\n)
The following code are
<?php
echo "Hello \n abhi";
?>
Source of the web page is contained to be displayed
output:- Hello abhi
* joining strings
Means to Concatenate(add together)Strings use the(.)
period character
<?php
$First_Name="abhi";
$Last_Name="Gautam";
echo $First_Name."".$Last_Name;
?>
Write to
create an upload file form?
Ans: uploading a file mean such as photographs and textual captions for
these photographs to the websites to get user and their friends to visit the
website often that it is basically upload a picture to server so that our
website looks very albactively incase interface must be created first that will
allow user to have a standard way for communicating with the website
The HTML code of uploading a file
<html>
<head>
<tittle> file upload</tittle>
</head>
<body>
<formENCtype=”Multipart/form-data” Action=”upload.php” Method=”POST”>
<input type=”file” Name=”file name”/>
<input type=”submit” value=”uploadfile”/>
</form>
</body>
</html>
Enc type=”Multipart/Form_data”:- Necessary for the form element of the type
file to function properly
Action:- The Name of the PHP Page that hold the code specification that
actually upload file to web server. This look as
|_____________|Browse—
|Upload|
When you click Browse button is click a directory tree is displayed.it is
the structure of the hard disk it is a temporary storage on the web server in
case programmer has to make use of the $_FILES associative array, created &
Maintained by the web server
Where $_FILES array is automatically store all information about files
uploaded to it is also called array index value is bound to each array index
$_FILES array contains the original path from where the user uploaded
files
There are another element Tmp_name
index of $_FILE array contain the path Where this file temporarily
stored on web server hard disk
Next Step is to call a built in MOVE_Uploaded_files. The Move
_Uploaded_files() requires the following parameter
1)
To path to where the temporary file is located on the web server.
2)
The path to where it should be moved to on web server
<?php
$target_path=”upload file”;
$target_path=$target_path.basename($FILE[uploaded files] [‘Name’]);
If(Move_uploaded_file($_File($_FILE)[‘uploading file’]
[‘tmp_name’],$target_path))
{
Echo”The file”.basename($_FILE[‘uploaded file’][‘Name’].”has been uploaded
sucessfully”);
}
Else
{
Echo”sorry there was an error please try again”;
}
?>
Write
Script to start a PHP session?
Ans: Session is a server side secure variable a session is a way to store
information to be used across multiple pages it store data on the server rather
than computer user in a session every user is identified or SID. The unique
session ID is used to link each user with their own information on the server
like Email,post etc. These ID are randomly generated on PHP
- Starting a PHP
Session:-
Before you can store any information in session variables you must first
start up the session to begin a new session simply call the PHP code
session_start()
<?php
Session_start();
?>
These function check firstly to see if a session already exixt by the
presence of a session IO if the session is already have it sets up the session
variable if doesn’t , it start a new session by creating a new session ID
- Storing & Accessing
Session Data
We can also store our session data
as key values pairs in the $_session[].it is a super global array. The stored data
can be accessed during lifetime of a session & register two Session
variable
<?php
// Starting Sression
Session_Start();
// Storing Session data
$_Session [“First Name”]=”Abhi”;
$_Session[“Last Name”]=”Gautam”;
?>
Accessing Session
<?php
Session_Start();
// Accessing Session data
Echo “Hi”,.$_Session[“First Name ”].’’,
$_Session [“Last Name”];
?>
Write a
Script to read a file character by character ?
Ans: TO read a file character by character using
Fget c ()
The Fget c () funcation returns a single character from an open file
Syntax:- Fget c (file)
Parameter
This function is slow & should not be used on Large files if you need
to read one character at a time from a large files use fgets() to read data one
line at a line one character at a time with Fget c ()
Example:-
<?php
$file=Fopen(“test2.txt”,”r”);
Echo fgetc ($ file);
Fclose ($ file);