0% found this document useful (0 votes)
4 views

Assignment WP

html

Uploaded by

uttam porwal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Assignment WP

html

Uploaded by

uttam porwal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Q.65. Explain the working of user defined function in JavaScript.

Ans.

 A function is a group of reusable code which can be called anywhere in


your program.
 In JavaScript, a user-defined function is a block of code designed to
perform a specific task, which can be executed whenever called within
the script.
1. Defining the Function
A function is created using the function keyword, followed by a
unique name, parentheses for parameters, and curly braces for the
function body.
2. Calling the Function
The function is executed by writing its name followed by parentheses
and any required arguments.
3. Return Values
Functions can return values using the return keyword, making them
useful for calculations or operations that need a result

Syntax:

<script type="text/javascript">

<!--

function functionname(parameter-list)

statements

//-->
</script>

Example:

<script type="text/javascript">

<!--

function sayHello()

alert("Hello there");

//-->

</script>

Output:

Hello there

Q.66. Explain built-in string function in JavaScript.

Ans.

 JavaScript comes with some inbuilt functions which include the string
function. Some of them are mentioned below;
 The String object lets you work with a series of characters; it wraps
Javascript's string primitive data type with a number of helper methods.
Syntax:
var val = new String(string);
 There is a list of methods available to manipulate and process text.
1. charAt() - Returns the character at the specified index.
Syntax:
string.charAt(index)
2. concat() - Combines the text of two strings and returns a new string.
Syntax:
string.concat(string2, string3[, ..., stringN]);
Example:
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );

document.write("Concatenated String :" + str3);


</script>
</body>
</html>
Output:
Concatenated String :This is string one This is string two
3. indexOf() - Returns the index within the calling String object of the
first occurrence of the specified value, or -1 if not found.
Syntax:
string.indexOf(searchValue[, fromIndex])
4. replace() - Used to find a match between a regular expression and a
string, and to replace the matched substring with a new substring.
Syntax:
string.replace(regexp/substr, newSubStr/function[, flags]);
5. slice() - Extracts a section of a string and returns a new string.
Syntax:
string.slice( beginslice [, endSlice] );
6. toUpperCase() - Returns the calling string value converted to
uppercase.
Syntax:
string.toUpperCase( )

Q.67. Explain built-in math function in JavaScript.

Ans.

 JavaScript comes with some inbuilt functions which include the string
function.
 The math object provides you properties and methods for mathematical
constants and functions.
 All the properties and methods of Math are static and can be called by
using Math as an object without creating it.
 Thus, you refer to the constant pi as Math.PI and you call the sine
function as Math.sin(x), where x is the method's argument.
Syntax:
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Some of the math functions are provided below;
1. abs() – Returns the absolute (positive) value of x
Example:
echo abs(-5);
Output:
5
2. round() – Rounds a number to the nearest integer or specified decimal
places.
Example:
echo round(5.679,2);
Output:
5.68
3. random() – Returns random floating number between 0 to 1.
Example:
echo rand(1,10);
Output:
Random number between 1 and 10.
4. Sqrt() – Returns the Square root of a number.
Example:
echo sqrt(16);
Output:
4
5. pow(x,y) – Returns the value of x to the power of y.
Example:
Echo pow(3,2);
Output:
9

Q.68. Explain built-in date function in JavaScript.

Ans.

 The Date object is a datatype built into the JavaScript language. Once a
Date object is created, a number of methods allow you to operate on it.
 Most methods simply allow you to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object, using either local
time or UTC (universal, or GMT) time.
Syntax:
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Some of the built-in functions are mentioned below;
1. Date() - Returns today's date and time
Syntax:
Date()
Example:
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt );
</script>
</body>
</html>
Output:
Date and Time : Wed Mar 25 2015 15:00:57 GMT+0530 (India
Standard Time)
2. getMonth() - Returns the month in the specified date according to
local time.
Syntax:
Date.getMonth ()
3. getTime() - Returns the numeric value of the specified date as the
number of milliseconds since January 1, 1970, 00:00:00 UTC.
Syntax:
Date.getTime ()
4. setDate() - Sets the day of the month for a specified date
according to local time.
Syntax:
Date.setDate( dayValue )
5. setTime() - Sets the Date object to the time represented by a
number of milliseconds since January 1, 1970,
00:00:00 UTC.
Syntax:
Date.setTime(timeValue)

Q.69. Explain built-in array function in JavaScript.

Ans.

 The Array object lets you store multiple values in a single variable. It
stores a fixed-size sequential collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.

Syntax:
var fruits = new Array( "apple", "orange", "mango" );
 Some of the built in functions of array are mentioned below;
1. concat() - Returns a new array comprised of this array joined with
other array(s) and/or value(s).
Syntax:
array.concat(value1, value2, ..., valueN);
Example:
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type="text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);


document.write("alphaNumeric : " + alphaNumeric );
</script>
</body>
</html>
Output:
alphaNumeric : a,b,c,1,2,3
2. forEach() - Calls a function for each element in the array.
Syntax:
array.forEach(callback[, thisObject]);
3. join() - Joins all elements of an array into a string.
Syntax:
array.join(separator);
4. splice() - Adds and/or removes elements from an array.
Syntax:
array.splice(index, howMany, [element1][, ..., elementN]);
5. sort() - Sorts the elements of an array.
Syntax:
array.sort( compareFunction );

Q.70. What is an Event? Explain various types of events i.e. onclick, onkeyup,
onblur?

Ans.

 JavaScript's interaction with HTML is handled through events that occur


when the user or the browser manipulates a page.
 When the page loads, it is called an event. When the user clicks a button,
that click too is an event. Other examples include events like pressing any
key, closing a window, resizing a window, etc.
Onclick event
 This is the most frequently used event type which occurs when a user
clicks the left button of his mouse. You can put your validation, warning
etc., against this event type.
Example:
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
document.write ("Hello World")
}
//-->
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type="
button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Output:
Click the following button and see result
Say Hello

Onkeyup Event

 The onkeyup event in JavaScript triggers each time a user releases a key
on the keyboard while focused on an element.
 It’s commonly used with input fields to capture and respond to user
typing in real-time, such as updating text, validating input, or performing
searches.
Example:
<html>
<head>
<title>onkeyup Event in JavaScript</title>
</head>
<body>
<input type="text" id="inputField" placeholder="Type something...">
<p id="displayText"></p> <script>
document.getElementById("inputField").onkeyup = function() {
let input = document.getElementById("inputField").value;
document.getElementById("displayText").innerText = "You typed: " +
input; };
</script>
</body>
</html>

Onblur Event

 The onblur event in JavaScript occurs when an element (like an input


field) loses focus, typically when the user clicks outside of it or tabs to
another element.
 It’s often used for actions like validating input after the user finishes
typing.
Example:
<html>
<head>
<title>onblur Event Example</title>
</head>
<body>
<input type="text" id="nameField" placeholder="Enter your name">
<p id="message"></p> <script>
document.getElementById("nameField").onblur = function() {
let input = document.getElementById("nameField").value;
if (input === "") {
document.getElementById("message").innerText = "Name cannot be
empty.";
} else {
document.getElementById("message").innerText = ""; } };
</script>
</body>
</html>
Q.71. Explain the working of user-defined functions in PHP.

Ans.

 PHP functions are similar to other programming languages. A function is


a piece of code which takes one more input in the form of parameter and
does some processing and returns a value.
 While creating a function its name should start with keyword function
and all the PHP code should be put inside { and } braces as shown in the
following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
Output:
You are really a nice person, Have a nice time!
 Once defined, a function can be called by its name, with or without
arguments, depending on its design. Each time it’s called, it executes its
block of code, outputting or returning a result as needed.
 Functions can return values to the calling code using return. This is
particularly useful for calculations or processing, where the result needs
to be stored or used later.

Q.72. Explain the built-in string function in PHP.

Ans.

 They are sequences of characters, like "PHP supports string operations".


 Singly quoted strings are treated almost literally, whereas doubly quoted
strings replace variables with their values as well as specially interpreting
certain character sequences.
1. String Concatenation Operator
 To concatenate two string variables together, use the dot (.) operator:
Example:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
Output:
Hello World 1234

2. Using the strlen() function


 The strlen() function is used to find the length of a string.
 The length of a string is often used in loops or other functions, when it is
important to know when the string ends.
Example:
<?php
echo strlen("Hello world!");
?>
Output:
12

3. Using the strpos() function


 The strpos() function is used to search for a string or character within a
string.
 If a match is found in the string, this function will return the position of
the first match. If no match is found, it will return FALSE.
Example:
<?php
echo strpos("Hello world!","world");
?>
Output:
6

Q.73. Explain the built-in math function in PHP.

Ans.

 PHP provides a range of built-in math functions to perform calculations


and handle mathematical operations. Here are some key ones:

1. abs($number): Returns the absolute (positive) value of a number.


Syntax:

echo abs(-5);

Output: 5

2. pow($base, $exp): Raises a number to the power of another.

Syntax:

echo pow(2, 3);

Output: 8

3. sqrt($number): Returns the square root of a number.

Syntax:

echo sqrt(16);

Output:

4. round($number, $precision): Rounds a number to the nearest integer or


specified decimal places.

Syntax:

echo round(5.678, 2);

Output:

5.68
5. max($array) and min($array): Finds the maximum or minimum value in
an array or set of numbers.

Syntax:

echo max(1, 3, 9);

Output: 9

6. rand($min, $max): Generates a random integer between specified limits.

Syntax:

Echo rand(1,10);

Output:

Random number between 1 and 10.

 These functions simplify mathematical tasks and improve efficiency in


PHP by offering quick, reliable calculations for common needs.

Q.74. Explain the built-in date function in PHP.

Ans.

 The date() function returns a formatted string representing a date. You


can exercise an enormous amount of control over the format that date()
returns with a string argument that you must pass to it.
1. date(format,timestamp)
 The date() optionally accepts a time stamp if omitted, then current date
and time will be used.
 Any other data you include in the format string passed to date() will be
included in the return value.
Example:
<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
Output:
11/04/24 11.15:06Today is 4 2024 November at 11.15 am
2. time(): Returns the current Unix timestamp (seconds since January 1,
1970).
Example:
echo time();
Output:
11.40.33.

3. getdate(timestamp): Returns an associative array with date and time


information.

Example:

print_r(getdate());

Output:

[32,30,7….]

Q.75. Explain the built-in array function in PHP.

Ans.
 An array is a data structure that stores one or more similar type of values
in a single value.
 PHP Array Functions allow you to interact with and manipulate arrays in
various ways.
1. array() – It creates an array.
Example:
<?php
$abc = array();
print_r($abc);
?>
Output:
Array()
2. array_push() - It adds elements to the end of the array.
Example:
ar = [1,2]
array_push(ar, 3);
Output:
[1,2,3]
3. array_merge() – It merges multiple arrays into one.
Example:
array1= [1,2];
array2= [3,4];
array_merge(array1,array2);
Output:
[1,2,3,4]
4. sort() – it sorts an array in ascending or descending order.
Example:
ar = [3, 1, 2];
sort(ar);
Output:
[1, 2, 3]
5. in_array(value,array) – It checks if a value exists in an array.
Example:
ar = [1,2,3];
if (in_array(2,ar)) {
echo “Found”;
}
Output:
Found

Q.76. Explain various looping structures in PHP.

Ans.

 Loops in PHP are used to execute the same block of code a specified
number of times. PHP supports following four loop types.
For loop
 The for statement is used when you know how many times you want to
execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment)
{
code to be executed;
}
Example:
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
Output:
At the end of the loop a=50 and b=25

While loop
 The while statement will execute a block of code if and as long as a test
expression is true.
 If the test expression is true, then the code block will be executed. After
the code has executed the test expression will again be evaluated and the
loop will continue until the test expression is found to be false.
Syntax:
while (condition)
{
code to be executed;
}
Example:
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
Output:
Loop stopped at i = 10 and num = 40

Do while loop
 The do...while statement will execute a block of code at least once - it
will then repeat the loop as long as a condition is true.
Syntax:
do
{
code to be executed;
}while (condition);
Example:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Output:
Loop stopped at i = 10

Foreach loop
 The foreach statement is used to loop through arrays. For each pass the
value of the current array element is assigned to $value and the array
pointer is moved by one and in the next pass next element will be
processed.
Syntax:
foreach (array as value)
{
code to be executed;
}
Example:
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

Q.77. Explain various conditional structures in PHP with example.

Ans.

 The if, elseif ...else and switch statements are used to take decision based
on the different condition.
 You can use conditional statements in your code to make your decisions.
If…else statement
 If you want to execute some code if a condition is true and another code
if a condition is false, use the if....else statement.
Syntax:
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
Output:
Have a nice weekend!

ElseIf Statement
 If you want to execute some code if one of the several conditions is true,
then use the elseif statement.
Syntax:
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
Output:
Have a nice weekend!

Switch Statement
 If you want to select one of many blocks of code to be executed, use the
Switch statement.
 The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax:
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
Example:
<html>
<body>
<?php
$d=date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>
Output:
Today is Friday

Q.78. Explain various PHP operators with example.

Ans.

Arithmetic Operator
It is used for basic mathematical operations.
Example:

<html>

<head><title>Arithmetical Operators</title><head>

<body>

<?php

$a = 42;

$b = 20;

$c = $a + $b;

echo "Addition Operation Result: $c <br/>";


$c = $a - $b;

echo "Subtraction Operation Result: $c <br/>";

$c = $a * $b;

echo "Multiplication Operation Result: $c <br/>";

$c = $a / $b;

echo "Division Operation Result: $c <br/>";

$c = $a % $b;

echo "Modulus Operation Result: $c <br/>";

$c = $a++;

echo "Increment Operation Result: $c <br/>";

$c = $a--;

echo "Decrement Operation Result: $c <br/>";

?>

</body>

</html>

Output:

Addition Operation Result: 62

Subtraction Operation Result: 22


Multiplication Operation Result: 840

Division Operation Result: 2.1

Modulus Operation Result: 2

Increment Operation Result: 42

Decrement Operation Result: 43

Comparison Operators

It is used to compare values.

Example:

<html>

<head><title>Comparison Operators</title><head>

<body>

<?php

$a = 42;

$b = 20;

if( $a == $b ){

echo "TEST1 : a is equal to b<br/>";

}else{

echo "TEST1 : a is not equal to b<br/>"; }


if( $a > $b ){

echo "TEST2 : a is greater than b<br/>";

}else{

echo "TEST2 : a is not greater than b<br/>";

if( $a < $b ){

echo "TEST3 : a is less than b<br/>";

}else{

echo "TEST3 : a is not less than b<br/>";

if( $a != $b ){

echo "TEST4 : a is not equal to b<br/>";

}else{

echo "TEST4 : a is equal to b<br/>";

if( $a >= $b ){

echo "TEST5 : a is either greater than or equal to b<br/>";

}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";

if( $a <= $b ){

echo "TEST6 : a is either less than or equal to b<br/>";

}else{

echo "TEST6 : a is neither less than nor equal to b<br/>";

?>

</body>

</html>

Output:

TEST1 : a is not equal to b

TEST2 : a is greater than b

TEST3 : a is not less than b

TEST4 : a is not equal to b

TEST5 : a is either greater than or equal to b

TEST6 : a is neither less than nor equal to b

Logical Operators
It is used to combine conditions.

Example:

<html>

<head><title>Logical Operators</title><head>

<body>

<?php

$a = 42;

$b = 0;

if( $a && $b ){

echo "TEST1 : Both a and b are true<br/>";

}else{

echo "TEST1 : Either a or b is false<br/>";

if( $a and $b ){

echo "TEST2 : Both a and b are true<br/>";

}else{

echo "TEST2 : Either a or b is false<br/>";

}
if( $a || $b ){

echo "TEST3 : Either a or b is true<br/>";

}else{

echo "TEST3 : Both a and b are false<br/>";

if( $a or $b ){

echo "TEST4 : Either a or b is true<br/>";

}else{

echo "TEST4 : Both a and b are false<br/>";

$a = 10;

$b = 20;

if( $a ){

echo "TEST5 : a is true <br/>";

}else{

echo "TEST5 : a is false<br/>";

if( $b ){
echo "TEST6 : b is true <br/>";

}else{

echo "TEST6 : b is false<br/>";

if( !$a ){

echo "TEST7 : a is true <br/>";

}else{

echo "TEST7 : a is false<br/>";

if( !$b ){

echo "TEST8 : b is true <br/>";

}else{

echo "TEST8 : b is false<br/>";

?>

</body>

</html>

Output:
TEST1 : Either a or b is false

TEST2 : Either a or b is false

TEST3 : Either a or b is true

TEST4 : Either a or b is true

TEST5 : a is true

TEST6 : b is true

TEST7 : a is false

TEST8 : b is false

Assignment Operators

It is used to assign values to variables.

Example:

<html>

<head><title>Assignment Operators</title><head>

<body>

<?php

$a = 42;

$b = 20;

$c = $a + $b; /* Assignment operator */


echo "Addition Operation Result: $c <br/>";

$c += $a; /* c value was 42 + 20 = 62 */

echo "Add AND Assignment Operation Result: $c <br/>";

$c -= $a; /* c value was 42 + 20 + 42 = 104 */

echo "Subtract AND Assignment Operation Result: $c <br/>";

$c *= $a; /* c value was 104 - 42 = 62 */

echo "Multiply AND Assignment Operation Result: $c <br/>";

$c /= $a; /* c value was 62 * 42 = 2604 */

echo "Division AND Assignment Operation Result: $c <br/>";

$c %= $a; /* c value was 2604/42 = 62*/

echo "Modulus AND Assignment Operation Result: $c <br/>";

?>

</body>

</html>

Output:

Addition Operation Result: 62

Add AND Assignment Operation Result: 104

Subtract AND Assignment Operation Result: 62


Multiply AND Assignment Operation Result: 2604

Division AND Assignment Operation Result: 62

Modulus AND Assignment Operation Result: 20

Conditional Operator

 There is one more operator called the conditional operator. It first


evaluates an expression for a true or false value and then executes one
of the two given statements depending upon the result of the
evaluation.
Example:
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otherwise b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>
Output:
TEST1 : Value of result is 20
TEST2 : Value of result is 10

Q.79. Explain array in PHP with suitable example.

Ans.

 An array is a data structure that stores one or more similar type of


values in a single value.
Numeric Array
 These arrays can store numbers, strings and any object but their index
will be represented by numbers. By default, the array index starts from
zero.
Example:
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Array
 The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index. Associative
array will have their index as string so that you can establish a strong
association between key and values.
Example:
<html>
<body>
<?php
/* First method to associate create array. */ $salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
Output:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Array
 A multi-dimensional array each element in the main array can also be
an array. And each element in the sub-array can be an array, and so
on. Values in the multi-dimensional array are accessed using multiple
index.
Example:
<html>
<body>
<?php
$marks = array(

"mohammad" => array


(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array

(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
Output:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

Q.80. Explain the differences between GET and POST methods in PHP.
Provide an example of how to use each method in a form.

Ans.

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 ? character.
 The GET method produces a long string that appears in your server
logs, in the browser's Location: box.
 The GET method is restricted to send up to 1024 characters only.
 GET Method is not ideal to be sent to the server if there is sensitive
information.
 GET can't be used to send binary data, like images or word
documents, to the server.
 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.
Example:
<?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="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

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 on data size to be
sent.
 The POST method can be 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 that your
information is secure.
 The PHP provides $_POST associative array to access all the sent
information using POST method.
Example:
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

Q.81. Write a PHP function to check if a given string is a palindrome. Please


provide an example of its usage.

Ans.

<?php

function isPalindrome($string) {

$cleanedString = strtolower(str_replace(' ', '', $string));

return $cleanedString === strrev($cleanedString); }

$word = "madam";

if (isPalindrome($word)) {

echo "$word is a palindrome.";

} else {

echo "$word is not a palindrome."; }

?>

Q.82. Describe how to connect to a MySQL database using PHP (PHP-MySQLi


connectivity). Write a simple code snippet that connects to a database and
checks for a successful connection.
Ans.

Opening a Database Connection

 PHP provides mysql_connect function to open a database connection.


This function takes five parameters and returns a MySQL link identifier
on success, or FALSE on failure.
Syntax:
connection mysql_connect(server,user,passwd,new_link,client_flag);
Parameters;
1. Server
Optional − The host name running database server. If not specified,
then
default value is localhost:3306.
2. User
Optional − The username accessing the database. If not specified, then
default
is the name of the user that owns the server process.
3. passwd

Optional − The password of the user accessing the database. If not


specified then default is an empty password.

4. new_link
Optional − If a second call is made to mysql_connect() with the same
arguments, no new connection will be established; instead, the
identifier of
the already opened connection will be returned.
5. client_flags
Optional − A combination of the following constants −
MYSQL_CLIENT_SSL − Use SSL encryption
MYSQL_CLIENT_COMPRESS − Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function
names
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout
seconds of inactivity before closing the connection.

Closing Database Connection

 Its simplest function mysql_close PHP provides to close a database


connection.
 This function takes connection resource returned by mysql_connect
function. It returns TRUE on success or FALSE on failure.
Syntax:
bool mysql_close ( resource $link_identifier );
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
Q.83. Describe how to create and select a database using PHP
(mysqli_select_db). Write a simple code snippet that connects to a
database and checks for a successful connect.

Ans.

Creating a Database

 To create and delete a database, you should have admin privilege. It’s
very easy to create a new MySQL database. PHP uses mysql_query
function to create a MySQL database.
 This function takes two parameters and returns TRUE on success or
FALSE on failure.
Syntax:
bool mysql_query( sql, connection );
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database test_db created successfully\n";
mysql_close($conn);
?>

Selecting a Database
 Once you establish a connection with a database server, then it is required
to select a particular database with which all your tables are associated.
 This is required because there may be multiple databases residing on a
single server and you can do work with a single database at a time.
 PHP provides function mysql_select_db to select a database. It returns
TRUE on success or FALSE on failure.
Syntax:
bool mysql_select_db( db_name, connection );
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'test_db' );
mysql_close($conn);
?>
Q.84. Describe how to create a table and insert a record using PHP. Write a
simple code snippet that connects to a database and checks for a
successful connection.

Ans.

 To create tables in the new database, you need to do the same thing as
creating the database. First create the SQL query to create the tables, then
execute the query using mysql_query() function.
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE TABLE employee( '.
'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>

 To insert records into the employee table in the above question;


Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
Q.85. Describe how to show a record of the table using PHP
(mysqli_fetch_row). Write a simple code snippet that connects to a
database and checks for a successful connection.

Ans.

 Data can be entered into MySQL tables by executing SQL INSERT


statement through PHP function mysql_query. Below a simple example
to insert a record into employee table.
 Data can be fetched from MySQL tables by executing SQL SELECT
statement through PHP function mysql_query.
 PHP provides another function called mysql_fetch_assoc() which also
returns the row as an associative array.
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

You might also like