0% found this document useful (0 votes)
58 views74 pages

PHP Imp

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views74 pages

PHP Imp

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

PART A

1. Write PHP statements to insert data into MySQL table.


```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO tablename (column1, column2) VALUES ('value1', 'value2')";


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
```

2. What is a protocol?
A protocol is a set of rules and conventions for communication between network devices.
It defines how data is transmitted and received over a network, ensuring that devices can
understand and interpret the data correctly.
3. Write short note on `<tag>`.
The `<tag>` element in HTML is used to define the start and end of a tag. Tags are the
building blocks of an HTML document and are used to create elements such as paragraphs,
headings, links, and other content.

4. Explain `<tag>` in HTML.


In HTML, a `<tag>` is used to create an element that can contain text, attributes, and other
elements. Tags are enclosed in angle brackets, with a start tag (e.g., `<p>`) and an end tag
(e.g., `</p>`), which together define the content and structure of the HTML document.

5. When is an internal CSS used in an HTML document?


Internal CSS is used when styles need to be applied to a single HTML document. It is
defined within the `<style>` tag inside the `<head>` section of the document. This method is
useful for defining unique styles for one specific page.

6. What is the use of the 'new' operator in JavaScript?


The `new` operator in JavaScript is used to create an instance of an object. It initializes an
object with the properties and methods defined in its constructor function.
```javascript
function Car(model) {
this.model = model;
}
var myCar = new Car("Toyota");
```

7. What is the syntax of Prompt Box in JavaScript? Explain.


The syntax of a prompt box in JavaScript is:
```javascript
var result = prompt("message", "default");
```
The `prompt` function displays a dialog box with a message, an input field, and OK/Cancel
buttons. It returns the user's input as a string. If the user clicks Cancel, it returns `null`.

8. How to start and finish a PHP block of code?


A PHP block of code starts with `<?php` and ends with `?>`.
```php
<?php
// PHP code goes here
?>
```

9. What are associative arrays in PHP?


Associative arrays in PHP are arrays where the keys are named strings rather than
numerical indices. They allow for more descriptive key names.
```php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43");
```

10. What is the use of `substr()` function in PHP?


The `substr()` function in PHP is used to extract a part of a string. It takes the string, the
starting position, and the length of the substring as parameters.
```php
$str = "Hello world";
echo substr($str, 6); // Outputs "world"
```

11. What are Cookies?


Cookies are small pieces of data stored on the client side (in the user's browser) that are
used to remember information between web pages or visits. They are commonly used for
session management, personalization, and tracking user behavior.
12. What is the purpose of the update command?
The `UPDATE` command in SQL is used to modify existing records in a database table. It
can change one or more fields in one or more records.
```sql
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
```

13. What is an Event? Give example.


An event in programming, especially in the context of user interfaces and web
development, is an action or occurrence detected by the program, such as a user clicking a
button, hovering over an element, or pressing a key.
Example:
```javascript
document.getElementById("myButton").onclick = function() {
alert("Button clicked!");
};
```

14. How functions and methods differ in JavaScript?


In JavaScript, functions are standalone blocks of code that perform a specific task and can
be called independently. Methods, on the other hand, are functions that are associated with
an object and can be called as a property of that object.
```javascript
// Function
function greet() {
return "Hello";
}

// Method
var person = {
name: "John",
greet: function() {
return "Hello " + this.name;
}
};
```

15. Which are the primary categories of data types in MySQL?


The primary categories of data types in MySQL are:
- Numeric: INT, FLOAT, DOUBLE
- String: CHAR, VARCHAR, TEXT
- Date and Time: DATE, DATETIME, TIMESTAMP
- Binary: BLOB, BINARY

16. Using Switch-Case write JavaScript code to display the name of day for a numeric input
(e.g. 1- Sunday, 2-Monday, ….)
```javascript
var dayNumber = 3;
var dayName;

switch (dayNumber) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
}

console.log(dayName);
```

17. What is internet?


The Internet is a global network of interconnected computers and servers that
communicate using standardized protocols. It allows for the exchange of information and
access to various services such as the World Wide Web, email, and file sharing.

18. How to insert images in a webpage?


To insert images in a webpage, use the `<img>` tag with the `src` attribute specifying the
path to the image file.
```html
<img src="image.jpg" alt="Description of image">
```

19. Explain password input control in HTML.


The password input control in HTML is created using the `<input>` tag with the
`type="password"` attribute. It allows users to enter passwords, which are displayed as
masked characters for privacy.
```html
<input type="password" name="user_password">
```

20. What is a CSS shorthand property? Give example.


A CSS shorthand property allows you to set multiple CSS properties in one declaration,
simplifying the CSS code.
Example:
```css
margin: 10px 15px 20px 25px; /* Sets margin-top, margin-right, margin-bottom, and
margin-left */
```

21. What are pseudo classes in CSS?


Pseudo-classes in CSS are used to define the special state of an element. They can be used
to style an element when it is hovered over, focused on, or when it is the first child of its
parent, among other conditions.
Example:
```css
a:hover {
color: red;
}
```
22. List any four Number object methods in JavaScript.
Four Number object methods in JavaScript are:
- `toFixed()`
- `toPrecision()`
- `toString()`
- `valueOf()`

23. What is server side scripting?


Server-side scripting refers to scripts that are executed on the server rather than the
client's browser. It is used to create dynamic web pages and manage server-side operations
such as database interactions, session handling, and file processing. Examples include PHP,
Python, and Node.js.

24. How arrays are created in PHP?


Arrays in PHP are created using the `array()` function or by using square brackets.
```php
$array1 = array("value1", "value2", "value3");
$array2 = ["value1", "value2", "value3"];
```

25. What is a PHP Session?


A PHP session is a way to store information (variables) to be used across multiple pages.
Unlike cookies, session data is stored on the server.
```php
session_start();
$_SESSION["username"] = "JohnDoe";
```
26. Differentiate function overloading and function overriding.
- Function Overloading: This occurs when multiple functions with the same name but
different parameters are

defined in the same scope. (Note: PHP does not support function overloading natively.)
- Function Overriding: This occurs when a child class defines a method that already exists
in its parent class, thereby replacing the parent's method.
```php
class ParentClass {
function display() {
echo "Parent display";
}
}

class ChildClass extends ParentClass {


function display() {
echo "Child display";
}
}
```

27. Explain any two features of MySQL database.


- Scalability and Flexibility: MySQL supports large databases, up to 50 million rows or more
in a table. It is scalable and can handle multiple database operations efficiently.
- Security: MySQL provides a secure environment with support for SSL connections, data
encryption, and robust access control mechanisms to protect sensitive data.

28. Write PHP statements to update the data in MySQL table.


```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE tablename SET column1='value1' WHERE condition";


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>
```

29. What is a web browser?


A web browser is a software application used to access and interact with websites on the
Internet. Examples include Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge.

30. Explain `<marquee>` tag in HTML.


The `<marquee>` tag in HTML is used to create a scrolling text or image within a web
page. However, it is deprecated and not recommended for use in modern web development.
```html
<marquee>Scrolling text</marquee>
```
31. Write the importance of the `name` attribute of `<tag>`.
The `name` attribute in HTML is used to reference form data after the form is submitted. It
is important for identifying the elements within the form data that is sent to the server.
```html
<input type="text" name="username">
```

32. List out the possible values for the `text-align` property.
The possible values for the `text-align` property in CSS are:
- `left`
- `right`
- `center`
- `justify`

33. Write the syntax for creating an array object. Give example.
The syntax for creating an array object in JavaScript is:
```javascript
var arrayName = new Array(element1, element2, element3);
// Or
var arrayName = [element1, element2, element3];
```
Example:
```javascript
var fruits = ["Apple", "Banana", "Cherry"];
```

34. Write down the requirements to run PHP programs.


To run PHP programs, you need:
- A web server (such as Apache, Nginx, or IIS)
- PHP installed on the server
- A text editor to write PHP code
- (Optional) A database like MySQL if your PHP program interacts with a database

35. What is the difference between '==' and '===' operator in PHP?
- `==` checks for value equality, converting types if necessary.
- `===` checks for value and type equality, ensuring that the compared values are of the
same type.

36. What is the use of `explode()` function in PHP?


The `explode()` function in PHP is used to split a string by a specified delimiter into an
array of strings.
```php
$string = "one,two,three";
$array = explode(",", $string); // $array = ["one", "two", "three"]
```

37. List out the arguments for `setcookie()` function.


The `setcookie()` function in PHP takes the following arguments:
- `name` (required)
- `value` (optional, default is "")
- `expire` (optional, default is 0)
- `path` (optional, default is "/")
- `domain` (optional)
- `secure` (optional, default is FALSE)
- `httponly` (optional, default is FALSE)

38. What is the difference between `char` and `varchar` data types?
- `char`: Fixed-length string. Storage size is always the same regardless of the actual string
length.
- `varchar`: Variable-length string. Storage size depends on the actual length of the string,
up to a maximum limit.

39. Write a PHP script to delete data from MySQL database table.
```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "DELETE FROM tablename WHERE condition";


if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>
```
40. What is a web page?
A web page is a document that is displayed in a web browser and is accessible over the
Internet or an intranet. It is written in HTML and can include text, images, videos, and links
to other web pages.

41. How do you insert a comment in HTML?


In HTML, a comment is inserted using the `<!--` and `-->` tags.
```html
<!-- This is a comment -->
```

42. Which tag is used to set the caption of a table? Write the syntax.
The `<caption>` tag is used to set the caption of a table.
```html
<table>
<caption>Table Caption</caption>
<!-- Table content -->
</table>
```

43. Name any four form events.


Four form events in JavaScript are:
- `onsubmit`
- `onreset`
- `onfocus`
- `onblur`

44. What is PHP?


PHP (Hypertext Preprocessor) is a server-side scripting language designed for web
development. It is used to create dynamic and interactive web pages and can be embedded
into HTML.
45. How single line comments are used in PHP?
Single-line comments in PHP can be added using either `//` or `#`.
```php
// This is a single-line comment
# This is also a single-line comment
```

46. What is the peculiarity of `$_REQUEST[...]`?


The `$_REQUEST` superglobal array in PHP collects data from `$_GET`, `$_POST`, and
`$_COOKIE`. It is used to retrieve input values regardless of the request method.

47. Define constructor.


A constructor is a special method in a class that is automatically called when an object of
the class is created. It is used to initialize the object's properties.
```php
class MyClass {
function __construct() {
// Initialization code
}
}
```

48. How can we find the number of fields in a recordset or query?


In PHP, the `mysqli_num_fields()` function is used to find the number of fields in a result
set.
```php
$result = $mysqli->query("SELECT * FROM tablename");
$num_fields = $result->field_count;
```
49. Define HTTP protocol.
The Hypertext Transfer Protocol (HTTP) is an application layer protocol used for
transmitting hypermedia documents, such as HTML. It is the foundation of data
communication on the World Wide Web.

50. Write HTML script for linking our webpage on the internet.
```html
<a href="http://www.example.com">Visit Example</a>
```

51. Write the importance of `<tag>`.


In HTML, the `<tag>` element is a fundamental component used to define the structure
and content of a webpage. It is used to create elements like paragraphs, headings, links,
images, and more.

52. Which operator is used to find the data type of a JavaScript variable? Give example.
The `typeof` operator is used to find the data type of a JavaScript variable.
```javascript
var x = 42;
console.log(typeof x); // Outputs "number"
```

53. How variables are used in PHP?


Variables in PHP are used to store data and are defined with a `$` symbol followed by the
variable name. They can store different data types such as integers, strings, arrays, and
objects.
```php
$variableName = "value";
```
54. What is the use of `for-each` loop in PHP?
The `foreach` loop in PHP is used to iterate over arrays. It provides an easy way to access
each element

in an array without needing to use a counter.


```php
$array = array("one", "two", "three");
foreach ($array as $value) {
echo $value;
}
```

55. How default values can be assigned to function parameters in PHP?


Default values can be assigned to function parameters by specifying the default value in
the function definition.
```php
function myFunction($param1, $param2 = "default") {
// Function code
}
```

56. What is interface?


An interface in programming defines a contract that classes must adhere to. It specifies
methods that must be implemented by any class that implements the interface, without
providing the method's code.
```php
interface MyInterface {
public function myMethod();
}
```
57. How can we create a database in MySQL?
A database in MySQL can be created using the `CREATE DATABASE` statement.
```sql
CREATE DATABASE database_name;
```

58. What is a Domain Name?


A domain name is a human-readable address used to access websites on the Internet,
such as `example.com`. It maps to the IP address of the server where the website is hosted.

59. What are the different values of the `type` attribute in unordered HTML list?
The `type` attribute in an unordered HTML list (`<ul>`) can take the following values:
- `disc` (default)
- `circle`
- `square`

60. Write short note on rows attribute of `<tag>`.


The `rows` attribute in HTML is used with the `<textarea>` tag to specify the visible
number of lines in the text area.
```html
<textarea rows="4"></textarea>
```

61. What is the main advantage of using external CSS?


The main advantage of using external CSS is the separation of content and design. It allows
for consistent styling across multiple pages and makes it easier to maintain and update
styles.
62. What is web server?
A web server is a software application that serves web pages to users over the Internet or
an intranet. It handles HTTP requests, processes them, and sends back the corresponding
web pages.

63. What are indexed or numbered arrays in PHP?


Indexed or numbered arrays in PHP are arrays where the keys are numerical indices,
starting from 0.
```php
$array = array("value1", "value2", "value3");
```

64. Differentiate warnings and Notices.


- Warnings: Non-fatal errors in PHP that do not stop the execution of the script but
indicate potential issues. They are usually displayed when something minor goes wrong.
- Notices: Informational messages about potentially problematic code, such as using an
undefined variable. Notices do not stop script execution.

65. What is the use of `extends` keyword?


The `extends` keyword in PHP is used to create a subclass that inherits properties and
methods from a parent class, enabling inheritance.
```php
class ChildClass extends ParentClass {
// Class code
}
```

66. Which are the values returned by `mysql_list_fields()`?


The `mysql_list_fields()` function returns information about the fields (columns) in a result
set, including field name, type, and length. Note: This function is deprecated in newer
versions of PHP, and `mysqli` or `PDO` should be used instead.
PART B
Sure, here are the answers to the questions you provided. Each answer is given a detailed
explanation worth 5 marks.

1. How links are added into HTML document? (4)


Links in HTML are added using the `<a>` (anchor) tag. The `href` attribute specifies the URL
of the page the link goes to.

```html
<a href="https://www.example.com">Visit Example</a>
```

2. Differentiate frameborder and border attributes in HTML. (3)


- frameborder: Specifies whether or not to display a border around a frame in a frameset.
Values are "0" (no border) or "1" (border).
- border: Used with tables to specify the thickness of the border around the table cells.
Accepts a numeric value.

```html
<frameset cols="50%,50%">
<frame src="frame_a.html" frameborder="1">
<frame src="frame_b.html" frameborder="0">
</frameset>

<table border="2">
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</table>
```
3. Explain any five JavaScript array methods with example. (3)
- push(): Adds one or more elements to the end of an array.
- pop(): Removes the last element from an array.
- shift(): Removes the first element from an array.
- unshift(): Adds one or more elements to the beginning of an array.
- splice(): Adds/removes elements from an array.

```javascript
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.shift(); // [2, 3]
arr.unshift(0); // [0, 2, 3]
arr.splice(1, 1, 'a', 'b'); // [0, 'a', 'b', 3]
```

4. Explain the difference between Confirm box and Prompt box in JavaScript. (3)
- Confirm box: Displays a dialog box with a message, an OK button, and a Cancel button.
Returns `true` if the user clicks OK, and `false` if the user clicks Cancel.
- Prompt box: Displays a dialog box that prompts the user for input, along with OK and
Cancel buttons. Returns the input value if OK is clicked, and `null` if Cancel is clicked.

```javascript
// Confirm box example
if (confirm("Are you sure?")) {
// User clicked OK
} else {
// User clicked Cancel
}
// Prompt box example
let userInput = prompt("Enter your name:");
if (userInput !== null) {
// User entered something and clicked OK
} else {
// User clicked Cancel
}
```

5. How variables are used in PHP? (3)


Variables in PHP are declared with a `$` symbol followed by the variable name. They can
store different data types and are case-sensitive.

```php
<?php
$stringVar = "Hello, World!";
$intVar = 42;
$floatVar = 3.14;
$boolVar = true;

echo $stringVar; // Outputs: Hello, World!


?>
```

6. Explain datatypes in PHP. (3)


PHP supports various datatypes:
- String: Sequence of characters.
- Integer: Whole numbers.
- Float: Floating-point numbers.
- Boolean: True or false.
- Array: Collection of values.
- Object: Instance of a class.
- NULL: Represents a variable with no value.
- Resource: Reference to external resources like database connections.

```php
<?php
$str = "Hello";
$int = 123;
$float = 12.34;
$bool = true;
$arr = array(1, 2, 3);
$obj = (object) ['property' => 'value'];
$nullVar = null;
?>
```

7. Explain with example any 5 string handling functions used in PHP? (4)
- strlen(): Returns the length of a string.
- str_replace(): Replaces all occurrences of a search string with a replacement string.
- substr(): Returns a part of a string.
- strpos(): Finds the position of the first occurrence of a substring.
- strtolower(): Converts a string to lowercase.

```php
<?php
$str = "Hello, World!";
echo strlen($str); // Outputs: 13
echo str_replace("World", "PHP", $str); // Outputs: Hello, PHP!
echo substr($str, 7, 5); // Outputs: World
echo strpos($str, "World"); // Outputs: 7
echo strtolower($str); // Outputs: hello, world!
?>
```

8. Explain exception handling? (1)


Exception handling in programming is a mechanism to handle runtime errors. It uses `try`,
`catch`, and `finally` blocks to capture and manage exceptions without terminating the
program.

```php
<?php
try {
$result = 10 / 0;
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
} finally {
echo "This is always executed.";
}
?>
```

9. Write a PHP script to create a student table using the MySql database 'college', and list
the details of students who secured more than 80 marks. (1)

```php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "college";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create table
$sql = "CREATE TABLE students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
marks INT(3) NOT NULL
)";

if ($conn->query($sql) === TRUE) {


echo "Table students created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

// Insert sample data


$conn->query("INSERT INTO students (name, marks) VALUES ('John Doe', 85)");
$conn->query("INSERT INTO students (name, marks) VALUES ('Jane Smith', 78)");
$conn->query("INSERT INTO students (name, marks) VALUES ('Sam Brown', 92)");
// Select students with marks greater than 80
$result = $conn->query("SELECT * FROM students WHERE marks > 80");

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Marks: " . $row["marks"]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>
```

10. Write short note on text formatting tags in HTML. (2)


HTML provides several text formatting tags to style and format text:
- `<b>`: Bold text.
- `<i>`: Italic text.
- `<u>`: Underlined text.
- `<strong>`: Important text (usually bold).
- `<em>`: Emphasized text (usually italic).
- `<mark>`: Highlighted text.
- `<small>`: Smaller text.
- `<del>`: Strikethrough text.
- `<ins>`: Inserted text.
```html
<p>This is <b>bold</b> and <i>italic</i> text. This is <u>underlined</u> and
<mark>highlighted</mark> text.</p>
```

11. Explain hyperlinks in HTML document with examples. (1)


Hyperlinks are created using the `<a>` tag. The `href` attribute specifies the URL.

```html
<a href="https://www.example.com">Visit Example</a>
```

12. Discuss CSS Font properties in detail. (1)


CSS font properties control the appearance of text. They include:
- font-family: Specifies the font.
- font-size: Specifies the size of the font.
- font-weight: Specifies the weight of the font (boldness).
- font-style: Specifies the style of the font (italic, normal).
- font-variant: Specifies whether the text should be displayed in small-caps.
- line-height: Specifies the line height.

```css
p{
font-family: Arial, sans-serif;
font

-size: 16px;
font-weight: bold;
font-style: italic;
line-height: 1.5;
}
```

13. Create a string object in JavaScript and apply any four built-in String object methods. (1)

```javascript
let str = new String("Hello, World!");
console.log(str.length); // Outputs: 13
console.log(str.toUpperCase()); // Outputs: HELLO, WORLD!
console.log(str.substring(0, 5)); // Outputs: Hello
console.log(str.indexOf("World")); // Outputs: 7
```

14. How comments are used in PHP? Give example. (2)


PHP supports single-line and multi-line comments:
- Single-line comments use `//` or `#`.
- Multi-line comments use `/* */`.

```php
<?php
// This is a single-line comment
# This is also a single-line comment

/*
This is a multi-line comment
spanning multiple lines
*/

echo "Hello, World!"; // This comment is on the same line as the code
?>
```

15. Explain operators in PHP. (3)


PHP operators are used to perform operations on variables and values:
- Arithmetic Operators: `+`, `-`, `*`, `/`, `%`
- Assignment Operators: `=`, `+=`, `-=`, `*=`, `/=`
- Comparison Operators: `==`, `!=`, `===`, `!==`, `<`, `>`, `<=`, `>=`
- Logical Operators: `&&`, `||`, `!`
- Increment/Decrement Operators: `++`, `--`
- String Operators: `.` (concatenation), `.=`

```php
<?php
$a = 10;
$b = 20;

// Arithmetic
echo $a + $b; // Outputs: 30

// Assignment
$a += $b; // $a is now 30

// Comparison
var_dump($a == $b); // Outputs: bool(false)

// Logical
var_dump($a > $b && $b > 0); // Outputs: bool(true)
// Increment/Decrement
$a++; // $a is now 31

// String
$str = "Hello" . " World"; // $str is "Hello World"
?>
```

16. Differentiate isset() and unset() functions in PHP. (1)


- isset(): Checks if a variable is set and is not `null`.
- unset(): Destroys the specified variable.

```php
<?php
$var = "Hello, World!";
var_dump(isset($var)); // Outputs: bool(true)

unset($var);
var_dump(isset($var)); // Outputs: bool(false)
?>
```

17. Which are the error levels used in PHP? (1)


PHP error levels include:
- `E_ERROR`
- `E_WARNING`
- `E_PARSE`
- `E_NOTICE`
- `E_CORE_ERROR`
- `E_CORE_WARNING`
- `E_COMPILE_ERROR`
- `E_COMPILE_WARNING`
- `E_USER_ERROR`
- `E_USER_WARNING`
- `E_USER_NOTICE`
- `E_STRICT`
- `E_RECOVERABLE_ERROR`
- `E_DEPRECATED`
- `E_USER_DEPRECATED`
- `E_ALL` (all errors and warnings, except `E_STRICT` in PHP 5.4.0 and later)

18. Explain the features of MySql database. (1)


MySQL is a popular open-source relational database management system known for its:
- Performance: High-speed and high-performance database operations.
- Reliability: Strong data integrity and transactional capabilities.
- Scalability: Supports large databases and numerous users.
- Flexibility: Can be used for various applications, supports multiple storage engines.
- Security: Strong data protection with multiple security layers.
- Community: Large and active user community.

19. Explain paragraphs and heading tags in HTML. (1)


- Paragraphs (`<p>`): Used to define a block of text. Browsers automatically add some
space before and after paragraphs.
- Headings (`<h1>` to `<h6>`): Used to define headings, with `<h1>` being the highest
(most important) level and `<h6>` the lowest.

```html
<h1>This is an H1 heading</h1>
<p>This is a paragraph.</p>
<h2>This is an H2 heading</h2>
<p>This is another paragraph.</p>
```

20. Explain the `<div>` tag in HTML. (1)


The `<div>` tag defines a division or section in an HTML document. It is used as a container
for other HTML elements and is often styled using CSS or manipulated with JavaScript.

```html
<div>
<h1>This is inside a div</h1>
<p>This paragraph is also inside the div.</p>
</div>
```

21. Discuss comparison and assignment operators in JavaScript. Give example. (1)

```javascript
// Comparison Operators
let x = 5;
let y = 10;

console.log(x == y); // false


console.log(x != y); // true
console.log(x === 5); // true
console.log(x !== '5'); // true
console.log(x > y); // false

// Assignment Operators
let z = 20;
z += 10; // z is now 30
z -= 5; // z is now 25
z *= 2; // z is now 50
z /= 5; // z is now 10
```

22. Explain different Decision Control Statements in JavaScript. (1)


Decision control statements in JavaScript include:
- if: Executes a block of code if a specified condition is true.
- else: Executes a block of code if the same condition is false.
- else if: Specifies a new condition to test if the first condition is false.
- switch: Selects one of many blocks of code to be executed.

```javascript
let num = 10;

if (num > 5) {
console.log("Number is greater than 5");
} else if (num == 5) {
console.log("Number is 5");
} else {
console.log("Number is less than 5");
}

switch (num) {
case 5:
console.log("Number is 5");
break;
case 10:
console.log("Number is 10");
break;
default:
console.log("Number is neither 5 nor 10");
}
```

23. Explain any three display statements available in PHP. (1)


- echo: Outputs one or more strings.
- print: Outputs a string. Returns 1, so it can be used in expressions.
- printf: Outputs a formatted string.

```php
<?php
echo "Hello, World!"; // Outputs: Hello, World!
print "Hello, PHP!"; // Outputs: Hello, PHP!
printf("Number: %d", 123); // Outputs: Number: 123
?>
```

24. Write a PHP program to find the factorial of a number. (1)

```php
<?php
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}

$num = 5;
echo "Factorial of $num is " . factorial($num);
?>
```

25. How PHP handles checkboxes and radio buttons in a form? Explain with example. (1)

```html
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="checkbox" name="vehicle[]" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle[]" value="Car"> I have a car<br>
<input type="radio" name="gender" value="Male"> Male<br>
<input type="radio" name="gender" value="Female"> Female<br>
<input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['vehicle'])) {
foreach ($_POST['vehicle'] as $vehicle) {
echo "You have a $vehicle<br>";
}
}
if (!empty($_POST['gender'])) {
echo "Gender: " . $_POST['gender'];
}
}
?>
```

26. Write short on visibility properties used in PHP class. (1)


PHP supports three visibility properties:
- public: Accessible from anywhere.
- protected: Accessible within the class itself and by inheriting and parent

classes.
- private: Accessible only within the class itself.

```php
<?php
class MyClass {
public $publicVar = "Public";
protected $protectedVar = "Protected";
private $privateVar = "Private";

function showVars() {
echo $this->publicVar; // Accessible
echo $this->protectedVar; // Accessible
echo $this->privateVar; // Accessible
}
}

$obj = new MyClass();


echo $obj->publicVar; // Accessible
// echo $obj->protectedVar; // Error
// echo $obj->privateVar; // Error
?>
```

27. What is the significance of the parameter array_type in mysql_fetch_array() function? (1)
The `array_type` parameter in `mysql_fetch_array()` determines how the fetched rows are
returned. It can be:
- `MYSQL_ASSOC` (or `MYSQLI_ASSOC`): Returns an associative array.
- `MYSQL_NUM` (or `MYSQLI_NUM`): Returns a numeric array.
- `MYSQL_BOTH` (or `MYSQLI_BOTH`): Returns both associative and numeric arrays.

```php
<?php
$result = mysqli_query($conn, "SELECT * FROM students");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
print_r($row); // Prints associative array
}
?>
```

28. Explain the four key concepts of HTML. (1)


- Elements: Building blocks of HTML, defined by tags (e.g., `<div>`, `<p>`).
- Attributes: Provide additional information about elements (e.g., `href` in `<a href="...">`).
- Tags: Define the beginning and end of an element (e.g., `<h1>`, `</h1>`).
- Document Structure: Hierarchical organization of HTML elements into a tree-like
structure.

```html
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
```

29. Write short note on attributes of `<input>` tag. (2)


The `<input>` tag attributes include:
- type: Specifies the type of input (e.g., `text`, `password`, `checkbox`, `radio`).
- name: Specifies the name of the input element.
- value: Specifies the initial value of the input element.
- placeholder: Specifies a short hint that describes the expected value.
- required: Specifies that the input field must be filled out.
- readonly: Specifies that the input field is read-only.
- disabled: Specifies that the input field is disabled.
- maxlength: Specifies the maximum number of characters allowed.

```html
<input type="text" name="username" placeholder="Enter your username" required>
<input type="password" name="password" maxlength="12">
<input type="checkbox" name="subscribe" value="newsletter"> Subscribe to newsletter
```

30. Write the importance of type attribute of input tag. Give examples. (1)
The `type` attribute of the `<input>` tag specifies the type of input control to display,
determining how the data is collected and displayed. Examples:
- `text`: Single-line text input.
- `password`: Text input that obscures the input characters.
- `radio`: Single-selection radio button.
- `checkbox`: Multi-selection checkbox.
- `submit`: Submit button.

```html
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="checkbox" name="agree" value="yes"> I agree to terms
<input type="submit" value="Submit">
```

31. Differentiate internal and external CSS. (1)


- Internal CSS: Defined within a `<style>` tag in the `<head>` section of an HTML
document. Used for applying styles to a single document.
- External CSS: Defined in a separate `.css` file. Linked to HTML documents using the
`<link>` tag in the `<head>` section. Can be used to apply styles to multiple documents.

```html
<!-- Internal CSS -->
<style>
body {
background-color: lightblue;
}
</style>

<!-- External CSS -->


<link rel="stylesheet" type="text/css" href="styles.css">
```

32. Name any five pseudo classes in CSS. Explain each. (1)
- :hover: Applies styles when the user hovers over an element.
- :active: Applies styles when an element is activated (e.g., clicked).
- :focus: Applies styles when an element has focus.
- :nth-child(n): Applies styles to the nth child of an element.
- :first-child: Applies styles to the first child of an element.

```css
a:hover {
color: red;
}
a:active {
color: blue;
}
input:focus {
border: 2px solid green;
}
p:nth-child(2) {
color: orange;
}
p:first-child {
color: purple;
}
```

33. Explain form validation and its importance. (1)


Form validation ensures that user input meets certain criteria before it is submitted. It can
be performed client-side (in the browser) or server-side (on the server). Importance
includes:
- Ensuring data integrity and accuracy.
- Preventing submission of incomplete or incorrect data.
- Enhancing user experience by providing immediate feedback.
- Reducing the risk of security vulnerabilities like SQL injection.

```html
<form onsubmit="return validateForm()">
<input type="text" name="username" id="username" required>
<input type="submit" value="Submit">
</form>

<script>
function validateForm() {
let x = document.getElementById("username").value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
```

34. State the features of PHP. (1)


PHP features include:
- Server-Side Scripting: PHP scripts are executed on the server.
- Cross-Platform: Runs on various platforms like Windows, Linux, Unix, etc.
- Database Integration: Supports numerous databases (e.g., MySQL, PostgreSQL).
- Error Reporting: Offers error reporting features.
- Open Source: Free to use and modify.
- Ease of Use: Simple syntax and extensive documentation.
- Extensible: Easily extended via modules and libraries.

35. What is a multidimensional array? How is it declared and used in PHP? Explain. (1)
A multidimensional array is an array containing one or more arrays. It's used to store data
in a matrix form.

```php
<?php
$multiArray = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);

// Accessing elements
echo $multiArray[0][1]; // Outputs: 2
echo $multiArray[2][0]; // Outputs: 7
?>
```

36. Explain the use of mysql_fetch_array() with the help of an example. (1)

```php
<?php
$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$result = mysqli_query($conn, "SELECT * FROM students");


while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}

mysqli_close($conn);
?>
```

37. How to create an HTML form? Explain with example. (1)

```html
<form action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
```

38. Explain how PHP manages Sessions. (1)


PHP sessions store user information across multiple pages. Session data is stored on the
server and is identified by a unique session ID.

```php
<?php
// Start session
session_start();

// Store session data


$_SESSION["username"] = "JohnDoe";

// Retrieve session data


echo "Username: " . $_SESSION["username"];

// Destroy session
session_destroy();
?>
```

39. What is polymorphism? Explain its use in PHP. (1)


Polymorphism allows methods to do different things based on the object it is acting upon.
In PHP, it is mainly achieved through inheritance and interfaces.

```php
<?php
interface Shape {
public function draw();
}

class Circle implements Shape {


public function draw() {
echo "Drawing Circle";
}
}
class Square implements Shape {
public function draw() {
echo "Drawing Square";
}
}

function drawShape(Shape $shape) {


$shape->draw();
}

$circle = new Circle();


$square = new Square();

drawShape($circle); // Outputs: Drawing Circle


drawShape($square); // Outputs: Drawing Square
?>
```

40. How will you create and use an array in PHP? Explain with example. (1)

```php
<?php
// Creating an indexed array
$fruits = array("Apple", "Banana", "Cherry");

// Accessing elements
echo $fruits[0]; // Outputs: Apple
// Creating an associative array
$ages = array("John" => 25, "Jane" => 30, "Smith" => 35);

// Accessing elements
echo $ages["John"]; // Outputs: 25

// Creating a multidimensional array


$students = array(
array("John", 25),
array("Jane", 30),
array("Smith", 35)
);

// Accessing elements
echo $students[1][0]; // Outputs: Jane
?>
```
PART C

1. Explain different types of Selectors in CSS. Give examples (1)

- Universal Selector: Selects all elements.


```css
*{
margin: 0;
padding: 0;
}
```
- Element Selector: Selects all elements of a given type.
```css
p{
color: blue;
}
```
- Class Selector: Selects all elements with a specific class attribute.
```css
.highlight {
background-color: yellow;
}
```
- ID Selector: Selects a single element with a specific ID attribute.
```css
#header {
font-size: 24px;
}
```
- Attribute Selector: Selects elements with a specific attribute.
```css
[type="text"] {
border: 1px solid black;
}
```
- Pseudo-class Selector: Selects elements based on their state.
```css
a:hover {
color: red;
}
```
- Pseudo-element Selector: Selects a part of an element.
```css
p::first-line {
font-weight: bold;
}
```

2. Explain
a) Datatypes in PHP.

PHP supports several data types:


- String: Sequence of characters.
```php
$string = "Hello, World!";
```
- Integer: Whole numbers.
```php
$int = 42;
```
- Float: Decimal numbers.
```php
$float = 3.14;
```
- Boolean: True or false values.
```php
$bool = true;
```
- Array: Collection of values.
```php
$array = array("apple", "banana", "cherry");
```
- Object: Instances of classes.
```php
class Car {
function Car() {
$this->model = "VW";
}
}
$herbie = new Car();
```
- NULL: Variable with no value.
```php
$var = NULL;
```
b) Operators in PHP.

PHP supports various operators:


- Arithmetic Operators: +, -, *, /, %, (exponentiation)
```php
$sum = 10 + 5; // 15
$product = 10 * 5; // 50
```
- Assignment Operators: =, +=, -=, *=, /=, %=
```php
$a = 10;
$a += 5; // 15
```
- Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
```php
if ($a == $b) { // Equal
// Code
}
```
- Logical Operators: &&, ||, !
```php
if ($a && $b) {
// Code
}
```
- Increment/Decrement Operators: ++, --
```php
$a++; // Increment
$b--; // Decrement
```

3. Design an HTML page to read name, register number and marks in three subjects of a
student. Write a PHP script to display the marksheet including total mark and percentage.
(1)

```html
<!DOCTYPE html>
<html>
<head>
<title>Student Marksheet</title>
</head>
<body>
<form action="marksheet.php" method="post">
Name: <input type="text" name="name"><br>
Register Number: <input type="text" name="reg_no"><br>
Subject 1 Marks: <input type="text" name="sub1"><br>
Subject 2 Marks: <input type="text" name="sub2"><br>
Subject 3 Marks: <input type="text" name="sub3"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```

```php
<!-- marksheet.php -->
<?php
$name = $_POST['name'];
$reg_no = $_POST['reg_no'];
$sub1 = $_POST['sub1'];
$sub2 = $_POST['sub2'];
$sub3 = $_POST['sub3'];

$total = $sub1 + $sub2 + $sub3;


$percentage = $total / 3;

echo "Name: $name<br>";


echo "Register Number: $reg_no<br>";
echo "Subject 1 Marks: $sub1<br>";
echo "Subject 2 Marks: $sub2<br>";
echo "Subject 3 Marks: $sub3<br>";
echo "Total Marks: $total<br>";
echo "Percentage: $percentage%<br>";
?>
```

4. Explain the commands:- CREATE, UPDATE, INSERT, DELETE, and SELECT (1)

- CREATE: Creates a new table or database.


```sql
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
);
```
- UPDATE: Modifies existing records in a table.
```sql
UPDATE students
SET age = 20
WHERE name = 'John';
```
- INSERT: Adds new records to a table.
```sql
INSERT INTO students (name, age)
VALUES ('Jane', 22);
```
- DELETE: Removes records from a table.
```sql
DELETE FROM students
WHERE name = 'John';
```
- SELECT: Retrieves data from a table.
```sql
SELECT * FROM students;
```

5. Explain various operators supported by JavaScript. Give examples. (2)

JavaScript supports several types of operators:

- Arithmetic Operators: +, -, *, /, %, (exponentiation)


```html
<script>
let x = 5 + 2; // 7
let y = 5 * 2; // 10
</script>
```
- Assignment Operators: =, +=, -=, *=, /=, %=
```html
<script>
let a = 10;
a += 5; // 15
</script>
```
- Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
```html
<script>
let b = 5;
let c = (b == 5); // true
</script>
```
- Logical Operators: &&, ||, !
```html
<script>
let d = true && false; // false
</script>
```
- Increment/Decrement Operators: ++, --
```html
<script>
let e = 5;
e++; // 6
</script>
```

6. Explain the following with examples: a) branching statements in PHP b) loops in PHP. (1)

a) Branching Statements in PHP


- if-else: Executes code based on a condition.
```php
<?php
$age = 18;
if ($age >= 18) {
echo "Adult";
} else {
echo "Not an Adult";
}
?>
```
- switch: Selects one of many blocks of code to execute.
```php
<?php
$color = "red";
switch ($color) {
case "red":
echo "Color is red";
break;
case "blue":
echo "Color is blue";
break;
default:
echo "Color is neither red nor blue";
}
?>
```

b) Loops in PHP
- for: Loops through a block of code a specified number of times.
```php
<?php
for ($i = 0; $i < 10; $i++) {
echo "The number is: $i <br>";
}
?>
```
- while: Loops through a block of code as long as the specified condition is true.
```php
<?php
$x = 1;
while ($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
```
- foreach: Loops through a block of code for each element in an array.
```php
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "$color <br>";
}
?>
```

7. How inheritance is implemented in PHP? Explain how base class methods and properties
are accessed? Give example. (1)

Inheritance in PHP is implemented using the `extends` keyword. A derived class inherits
methods and properties from a base class.

```php
<?php
class BaseClass {
public $baseProperty = "I am a base property";

public function baseMethod() {


echo "I am a base method

";
}
}

class DerivedClass extends BaseClass {


public function derivedMethod() {
echo "I am a derived method";
}
}

$obj = new DerivedClass();


echo $obj->baseProperty; // Accessing base class property
$obj->baseMethod(); // Accessing base class method
$obj->derivedMethod(); // Accessing derived class method
?>
```

8. With the help of an example explain each step for accessing the data from a MySql
database table. (2)

```php
<?php
// Step 1: Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Step 2: Check the connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Step 3: Write a SQL query


$sql = "SELECT id, name FROM students";

// Step 4: Execute the query


$result = mysqli_query($conn, $sql);

// Step 5: Check if there are results


if (mysqli_num_rows($result) > 0) {
// Step 6: Fetch data
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}

// Step 7: Close the connection


mysqli_close($conn);
?>
```

9. What are the different methods used to embed CSS into an HTML document? Explain
each with example. (1)

- Inline CSS: Using the `style` attribute within HTML tags.


```html
<p style="color: blue;">This is a blue paragraph.</p>
```
- Internal CSS: Using a `<style>` tag within the `<head>` section.
```html
<head>
<style>
p{
color: red;
}
</style>
</head>
<body>
<p>This is a red paragraph.</p>
</body>
```
- External CSS: Linking an external CSS file using the `<link>` tag.
```html
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<p>This paragraph is styled by an external stylesheet.</p>
</body>
```
`styles.css` file:
```css
p{
color: green;
}
```

10. Explain arrays in PHP with the help of examples. (1)

- Indexed Array: An array with numeric indices.


```php
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Outputs: Apple
?>
```
- Associative Array: An array with named keys.
```php
<?php
$ages = array("John" => 25, "Jane" => 30, "Smith" => 35);
echo $ages["John"]; // Outputs: 25
?>
```
- Multidimensional Array: An array containing one or more arrays.
```php
<?php
$students = array(
array("John", 25),
array("Jane", 30),
array("Smith", 35)
);
echo $students[1][0]; // Outputs: Jane
?>
```

11. Explain different categories of errors in PHP. What are the different error handling
mechanisms? (1)

- Categories of Errors:
- Notice: Minor errors, execution continues.
```php
$x = $undefinedVariable; // Notice: Undefined variable
```
- Warning: More significant errors, execution continues.
```php
include("nonexistentfile.php"); // Warning: include failed
```
- Fatal Error: Severe errors, stops execution.
```php
nonExistentFunction(); // Fatal error: Call to undefined function
```
- Error Handling Mechanisms:
- Using `die()` or `exit()`: Stops script execution.
```php
<?php
if (!file_exists("test.txt")) {
die("File not found");
}
?>
```
- Using `set_error_handler()`: Custom error handler.
```php
<?php
function customError($errno, $errstr) {
echo "Error: [$errno] $errstr";
}
set_error_handler("customError");
echo($test); // Triggers custom error handler
?>
```
- Using `try-catch` for Exceptions:
```php
<?php
try {
if (!file_exists("test.txt")) {
throw new Exception("File not found");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
```

12. Create a login page using PHP and MySql. (1)

- HTML Form:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="login.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
- PHP Script (login.php):
```php
<?php
$conn = mysqli_connect("localhost", "username", "password", "database");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE username='$username' AND


password='$password'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
echo "Login successful!";
} else {
echo "Invalid username or password";
}

mysqli_close($conn);
?>
```

13. Write notes on different JavaScript built-in objects. (1)

- String Object: Methods for string manipulation.


```html
<script>
let str = "Hello, World!";
console.log(str.length); // 13
console.log(str.toUpperCase()); // HELLO, WORLD!
console.log(str.substring(0, 5)); // Hello
</script>
```
- Array Object: Methods for array manipulation.
```html
<script>
let arr = [1, 2, 3, 4];
console.log(arr.length); // 4
console.log(arr.join("-")); // 1-2-3-4
arr.push(5);
console.log(arr); // [1, 2, 3, 4, 5]
</script>
```
- Date Object: Methods for date and time manipulation.
```html
<script>
let date = new Date();
console.log(date.getFullYear()); // Current year
console.log(date.getMonth()); // Current month (0-11)
console.log(date.getDate()); // Current day
</script>
```
- Math Object: Methods for mathematical operations.
```html
<script>
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
console.log(Math.random()); // Random number between 0 and 1
</script>
```
14. a) Write a PHP program to sort an array. b) Write a PHP program to find the factorial of a
number. (1)

a) Sorting an array:
```php
<?php
$numbers = array(4, 2, 8, 6);
sort($numbers);
foreach ($numbers as $num) {
echo "$num ";
}
?>
```
b) Finding the factorial of a number:
```php
<?php
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}

$num = 5;
echo "Factorial of $num is " . factorial($num);
?>
```
15. Explain decision control statements and loops in JavaScript. (1)

- Decision Control Statements:


- if-else: Executes code based on a condition.
```html
<script>
let age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Not an Adult");
}
</script>
```
- switch: Selects one of many code blocks to execute.
```html
<script>
let color = "red";
switch (color) {
case "red":
console.log("Color is red");
break;
case "blue":

console.log("Color is blue");
break;
default:
console.log("Color is neither red nor blue");
}
</script>
```

- Loops:
- for: Loops through a block of code a specified number of times.
```html
<script>
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
</script>
```
- while: Loops through a block of code as long as a specified condition is true.
```html
<script>
let x = 1;
while (x <= 5) {
console.log("The number is " + x);
x++;
}
</script>
```
- do-while: Loops through a block of code once, and then repeats the loop as long as a
specified condition is true.
```html
<script>
let y = 1;
do {
console.log("The number is " + y);
y++;
} while (y <= 5);
</script>
```

16. Discuss how PHP handles Sessions and Cookies. (1)

- Sessions: Used to store user information across multiple pages.


- Start a session:
```php
<?php
session_start();
$_SESSION['username'] = "JohnDoe";
?>
```
- Access session variables:
```php
<?php
session_start();
echo $_SESSION['username']; // Outputs: JohnDoe
?>
```
- Destroy a session:
```php
<?php
session_start();
session_unset();
session_destroy();
?>
```

- Cookies: Used to store user information on the client side.


- Set a cookie:
```php
<?php
setcookie("user", "JohnDoe", time() + (86400 * 30), "/");
?>
```
- Access a cookie:
```php
<?php
if(isset($_COOKIE['user'])) {
echo "User is " . $_COOKIE['user'];
}
?>
```
- Delete a cookie:
```php
<?php
setcookie("user", "", time() - 3600, "/");
?>
```
17. Explain MySql datatypes in detail. (1)

MySQL supports various datatypes:

- Numeric Types:
- INT: Integer, size 4 bytes.
- FLOAT: Floating-point number, size 4 bytes.
- DOUBLE: Double precision floating-point number, size 8 bytes.
- DECIMAL: Fixed-point number.

- Date and Time Types:


- DATE: Date value (YYYY-MM-DD).
- DATETIME: Date and time value (YYYY-MM-DD HH:MM:SS).
- TIMESTAMP: Timestamp value.

- String Types:
- CHAR: Fixed-length string.
- VARCHAR: Variable-length string.
- TEXT: Large string, up to 65,535 characters.
- BLOB: Binary large object.

- Spatial Types:
- GEOMETRY: Geometric data type.
- POINT: Point type.
- LINESTRING: Line string type.
18. Demonstrate the working of mysql_connect(), mysql_query(), mysql_fetch_array(), with
the help of an example. (1)

```php
<?php
// Connect to the database
$conn = mysql_connect("localhost", "username", "password");
mysql_select_db("database", $conn);

// Execute a query
$result = mysql_query("SELECT * FROM students");

// Fetch and display data


while ($row = mysql_fetch_array($result)) {
echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}

// Close the connection


mysql_close($conn);
?>
```

19. Explain in detail about string and array functions used in PHP with suitable examples. (1)

- String Functions:
- strlen(): Returns the length of a string.
```php
<?php
$str = "Hello";
echo strlen($str); // Outputs: 5
?>
```
- str_replace(): Replaces all occurrences of a search string with a replacement string.
```php
<?php
$str = "Hello World";
echo str_replace("World", "Dolly", $str); // Outputs: Hello Dolly
?>
```
- strpos(): Finds the position of the first occurrence of a substring in a string.
```php
<?php
$str = "Hello World";
echo strpos($str, "World"); // Outputs: 6
?>
```

- Array Functions:
- count(): Returns the number of elements in an array.
```php
<?php
$arr = array(1, 2, 3);
echo count($arr); // Outputs: 3
?>
```
- array_merge(): Merges one or more arrays.
```php
<?php
$arr1 = array("red", "green");
$arr2 = array("blue", "yellow");
$result = array_merge($arr1, $arr2);
print_r($result); // Outputs: Array ( [0] => red [1] => green [2] => blue [3] => yellow )
?>
```
- in_array(): Checks if a value exists in an array.
```php
<?php
$arr = array("red", "green", "blue");
echo in_array("green", $arr); // Outputs: 1 (true)
?>
```

You might also like