Assignment WP
Assignment WP
Ans.
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
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 );
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
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)
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];
Q.70. What is an Event? Explain various types of events i.e. onclick, onkeyup,
onblur?
Ans.
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
Ans.
Ans.
Ans.
echo abs(-5);
Output: 5
Syntax:
Output: 8
Syntax:
echo sqrt(16);
Output:
Syntax:
Output:
5.68
5. max($array) and min($array): Finds the maximum or minimum value in
an array or set of numbers.
Syntax:
Output: 9
Syntax:
Echo rand(1,10);
Output:
Ans.
Example:
print_r(getdate());
Output:
[32,30,7….]
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
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
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
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;
$c = $a * $b;
$c = $a / $b;
$c = $a % $b;
$c = $a++;
$c = $a--;
?>
</body>
</html>
Output:
Comparison Operators
Example:
<html>
<head><title>Comparison Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ){
}else{
}else{
if( $a < $b ){
}else{
if( $a != $b ){
}else{
if( $a >= $b ){
}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";
if( $a <= $b ){
}else{
?>
</body>
</html>
Output:
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 ){
}else{
if( $a and $b ){
}else{
}
if( $a || $b ){
}else{
if( $a or $b ){
}else{
$a = 10;
$b = 20;
if( $a ){
}else{
if( $b ){
echo "TEST6 : b is true <br/>";
}else{
if( !$a ){
}else{
if( !$b ){
}else{
?>
</body>
</html>
Output:
TEST1 : Either a or b is false
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
Assignment Operators
Example:
<html>
<head><title>Assignment Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
?>
</body>
</html>
Output:
Conditional Operator
Ans.
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
);
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(
(
"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>
Ans.
<?php
function isPalindrome($string) {
$word = "madam";
if (isPalindrome($word)) {
} else {
?>
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.
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);
?>
Ans.