PHP Imp
PHP Imp
$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.
// Method
var person = {
name: "John",
greet: function() {
return "Hello " + this.name;
}
};
```
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);
```
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";
}
}
$conn->close();
?>
```
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"];
```
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.
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->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.
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>
```
50. Write HTML script for linking our webpage on the internet.
```html
<a href="http://www.example.com">Visit Example</a>
```
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"
```
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`
```html
<a href="https://www.example.com">Visit Example</a>
```
```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
}
```
```php
<?php
$stringVar = "Hello, World!";
$intVar = 42;
$floatVar = 3.14;
$boolVar = true;
```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!
?>
```
```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 ($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();
?>
```
```html
<a href="https://www.example.com">Visit Example</a>
```
```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
```
```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
?>
```
```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"
?>
```
```php
<?php
$var = "Hello, World!";
var_dump(isset($var)); // Outputs: bool(true)
unset($var);
var_dump(isset($var)); // Outputs: bool(false)
?>
```
```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>
```
```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;
// 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
```
```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");
}
```
```php
<?php
echo "Hello, World!"; // Outputs: Hello, World!
print "Hello, PHP!"; // Outputs: Hello, PHP!
printf("Number: %d", 123); // Outputs: Number: 123
?>
```
```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'];
}
}
?>
```
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
}
}
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
}
?>
```
```html
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
```
```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">
```
```html
<!-- Internal CSS -->
<style>
body {
background-color: lightblue;
}
</style>
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;
}
```
```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>
```
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());
}
mysqli_close($conn);
?>
```
```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>
```
```php
<?php
// Start session
session_start();
// Destroy session
session_destroy();
?>
```
```php
<?php
interface Shape {
public function draw();
}
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
// Accessing elements
echo $students[1][0]; // Outputs: Jane
?>
```
PART C
2. Explain
a) Datatypes in PHP.
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'];
4. Explain the commands:- CREATE, UPDATE, INSERT, DELETE, and SELECT (1)
6. Explain the following with examples: a) branching statements in PHP b) loops in PHP. (1)
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";
";
}
}
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");
9. What are the different methods used to embed CSS into an HTML document? Explain
each with example. (1)
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();
}
?>
```
- 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'];
if (mysqli_num_rows($result) > 0) {
echo "Login successful!";
} else {
echo "Invalid username or password";
}
mysqli_close($conn);
?>
```
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)
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>
```
- 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.
- 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");
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)
?>
```