1. Home
  2. Docs
  3. Web Technology II
  4. Model Question Solution – PHP

Model Question Solution – PHP

1.) What is server-side script?

  • A server-side script is a program executed on the web server to generate dynamic web content, process data, and handle requests from clients.
  • It typically interacts with databases, manages sessions, and performs complex operations

2.) What is PHP superglobal?

  • Super Global i.e. (Global Variable) are built-in variables that are accessible from any part of a script without needing to explicitly declare them as global.
  • Examples include $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_SERVER, $_REQUEST, $_ENV, and $GLOBALS.

3.) Define associative array.

  • An associative array is an array that uses named keys instead of numeric indexes to access its elements. These keys act as identifiers for the values, making it easier to work with data that has labels.

4.) What is static method?

  • A static method in PHP is a method that belongs to the class rather than instances of the class.
  • It can be called directly using the class name without needing to create an object of the class.

5.) Why do we need file handling?

  • File handling allows PHP scripts to read from, write to, and modify files on the server. This is essential for tasks like saving user data, logs, configuration files, and handling file uploads.

6.) List some benefits of storing website data in databases.

  • Databases provide organized, efficient, and secure storage for data.
  • They enable easy retrieval, updating, and deletion of data, ensure data integrity, and allow for advanced querying, sorting, and filtering of information.

7.) What is cookie?

  • Cookies are small pieces of data stored on the client-side (browser) that are sent to and from the server with each HTTP request.

8.) What are the uses of session?

  • Sessions are used to store user-specific information on the server, such as login status, preferences, or shopping cart data.
  • Data stored in a session is accessible across multiple pages.

9.) What is server-side framework?

  • A server-side web framework is a set of tools, libraries, and conventions that helps developers build web applications more efficiently.

10.) What is dynamic website?

  • A dynamic website is one that generates content in real-time based on user input, data from a database, or other factors.
  • Unlike static websites, dynamic sites display different content to users based on their interactions (e.g., e-commerce websites, social media platforms).

11.) Compare $_GET with $_POST.

image 24

12.) Explain regular expression with example.

  • A regular expression (regex) is a sequence of characters used as a search pattern. It is used to find or match patterns in strings, such as email addresses, phone numbers, or specific characters.
$string = "Hello, my email is test@example.com!";
$pattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/";
preg_match($pattern, $string, $matches);
print_r($matches);

13.) How do you set and get cookies in PHP?

  • Setting a cookie in PHP:
setcookie("user", "JohnDoe", time() + (86400 * 30), "/"); // expires in 30 days
  • Getting a cookie in PHP:
if(isset($_COOKIE["user"])) {
    echo "Hello " . $_COOKIE["user"];
} else {
    echo "Cookie is not set.";
}
  • This sets a cookie called user with the value JohnDoe, which will expire in 30 days. The value can be accessed using $_COOKIE.

14.) How do you access to user credentials from PHP?

User credentials (such as username and password) are typically submitted via an HTML form and accessed in PHP using $_POST.

<!DOCTYPE html>
<html>
<body>
    <form action="" method="post">
        Username: <input type="text" name="username"><br>
        Password: <input type="password" name="password"><br>
        <input type="submit" value="Submit">
    </form>
    
    <?php
    // Check if the form is submitted
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // Access user credentials from the form
        $username = $_POST['username'];
        $password = $_POST['password'];

        // Display the credentials (for demonstration purposes only; don't do this in production)
        echo "Username: " .$username . "<br>";
        echo "Password: " . $password;
    } 
    ?>
</body>
</html>

15.) Discuss some benefits of server-side frameworks.

  • Faster Development: Frameworks come with pre-built modules, libraries, and tools to speed up development, reducing the need to write repetitive code.
  • Security: Many frameworks have built-in security features such as input validation, session management, and protection against common attacks like SQL injection.
  • Maintainability: A server-side framework provides structure to the codebase, making it easier to manage and scale applications.
  • Community Support: Most popular frameworks have active communities, offering documentation, tutorials, and help for troubleshooting.
  • Database Integration: Frameworks typically offer simplified methods for interacting with databases (e.g., ORM), making CRUD operations easier and more efficient.

16.) How do you define a class in PHP? Explain with suitable example.

  • In PHP, a class is defined using the class keyword.
  • A class in PHP is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects of the class will have.
class Car {
    // Properties
    public $model;
        
    // Constructor
    public function __construct($model) {
        $this->model = $model;
    }

    // Method
    public function displayCarInfo() {
        echo "Car: $this->model";
    }
}

// Creating an object
$car1 = new Car("Toyota");
$car1->displayCarInfo();

17.) How do you create functions in PHP? Explain with example.

  • In PHP, functions are defined using the function keyword. Functions allow you to group a set of statements together to perform a specific task, which can be reused multiple times throughout the code. Functions may accept arguments (parameters) and return a value.

Syntax for defining a function:

function function_name($param1, $param2) {
    // Function body
    return $result;
}

Example:

<?php
// Define a function to calculate the area of a rectangle
function calculateArea($length, $width) {
    $area = $length * $width; // Calculate the area
    return $area; // Return the area
}

// Call the function and store the result in a variable
$area = calculateArea(5, 10); // Pass 5 as length and 10 as width
echo "The area of the rectangle is: " . $area;
?>

Explanation:

  • calculateArea() is the function name, which accepts two parameters ($length and $width).
  • The function calculates the area and returns the result.
  • The function is called with values 5 and 10 for length and width, and the result is stored in the $area variable, which is then echoed to the screen.

18.) How do you handle exceptions in PHP?

  • In PHP, exceptions are handled using the try, catch, and throw blocks. Exceptions are used to handle errors or exceptional conditions during program execution.

Basic Structure:

  • try block: Code that may throw an exception.
  • catch block: Code that handles the exception.
  • throw keyword: Used to throw an exception manually.

Example of Exception Handling in PHP:

<?php
// Function that throws an exception
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    return $a / $b;
}

// Using try-catch block for exception handling
try {
    echo divide(10, 2); // Valid division
    echo "\n";
    echo divide(10, 0); // This will throw an exception
} catch (Exception $e) {
    // Handle the exception
    echo "Error: " . $e->getMessage();
}
?>

19.) Write a program in PHP that reads a file and displays vowels only.

  • To read a file in PHP, we can use functions like fopen(), fgets(), or file_get_contents(). For this example, we’ll read a file line by line and display only the vowels in the content.
<?php
// Specify the file to read
$filename = "example.txt";

// Check if the file exists
if (file_exists($filename)) {
    // Read the content of the file
    $content = file_get_contents($filename);
    
    // Filter vowels (case-insensitive)
    $vowels = preg_replace('/[^aeiouAEIOU]/', '', $content);

    // Display the vowels
    echo "Vowels in the file are: " . $vowels;
} else {
    echo "File does not exist.";
}
?>

Output (Assuming the content of sample.txt is “Hello World”):

e o o

20.) Explain the process of connecting a PHP program with the database and inserting data
into it

  • In PHP, connecting to a database is done using either mysqli or PDO. Here’s an example of connecting to a MySQL database and inserting data using the mysqli extension.

Steps for connecting to a MySQL Database:

  • Create a Database Connection: Use mysqli_connect() to connect to the database.
  • Insert Data into the Database: Use SQL queries to insert data into a table.
  • Close the Connection: Always close the database connection once you’re done.
<?php
// Step 1: Create a database connection
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";

// Create connection
$conn = mysqli_connect($server, $username, $password, $database);

// Check if the connection was successful
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Step 2: Insert data into the database
$name = "John Doe";
$email = "john@example.com";
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// Step 3: Close the connection
mysqli_close($conn);
?>

Explanation:

  • We first create a connection to the database test_db using the mysqli_connect() function.
  • After checking that the connection is successful, we define an SQL query to insert a new user (John Doe with an email).
  • The query is executed using mysqli_query(). If the query is successful, it outputs a success message; otherwise, it shows the error.
  • Finally, the connection is closed using mysqli_close().

21.) Write a server-side script in PHP to illustrate inserting and retrieving data to and from the database table. Create required connection using your own assumptions. Use HTML form to insert and display data.

<?php
// Establish Database Connection
$servername = "localhost";
$username = "root";
$password = "";
$database = "example_db";

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

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

// Handle Form Submission for Data Insertion
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];

    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully.<br>";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Fetch Data from Database
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Insert and Retrieve Data</title>
</head>
<body>
    <h1>Insert Data</h1>
    <form method="POST" action="">
        Name: <input type="text" name="name" required><br>
        Email: <input type="email" name="email" required><br>
        <button type="submit">Submit</button>
    </form>

    <h2>Retrieved Data</h2>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <?php
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['email']}</td></tr>";
            }
        } else {
            echo "<tr><td colspan='3'>No data found</td></tr>";
        }
        ?>
    </table>
</body>
</html>

<?php
$conn->close();
?>

22.) . What are the benefits of using arrays? Write a program to display sum and average of 10 numbers stored in a PHP array. Why do we need associative arrays?

An array in PHP is a data structure that allows you to store multiple values in a single variable. Arrays can hold data of any type (integers, strings, objects, etc.), and the values can be accessed using indices or keys.

PHP supports three types of arrays:

  • Indexed Arrays: Use numeric indices to access elements.
  • Associative Arrays: Use named keys to access elements.
  • Multidimensional Arrays: Contain arrays within arrays.

Benefits of Using Arrays

‣ Efficient Data Storage:

  • Arrays allow the storage of multiple values in a single variable, reducing the need for separate variables.

‣ Ease of Iteration:

  • Arrays can be iterated through using loops (e.g., for or foreach), making it easier to handle large datasets.

‣ Dynamic Resizing:

  • PHP arrays can dynamically grow or shrink as elements are added or removed.

‣ Versatility:

  • Arrays can store any type of data (numbers, strings, objects), and you can mix data types in the same array.

‣ Associative Keys:

  • With associative arrays, meaningful keys can be used instead of numeric indices, improving code readability and data access.

Program to Display Sum and Average of 10 Numbers Stored in an Array

<?php
// Declare an indexed array with 10 numbers
$numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];

// Calculate the sum of all numbers
$sum = array_sum($numbers);

// Calculate the average
$average = $sum / count($numbers);

// Display the sum and average
echo "The sum of the numbers is: $sum<br>";
echo "The average of the numbers is: $average<br>";
?>

Associative arrays are arrays that use named keys instead of numeric indices. They are essential when you want to represent data with meaningful labels, making your code more readable and organized.

Advantages of Associative Arrays:

Improved Readability:

  • Named keys (e.g., name, email) are more descriptive than numeric indices.
  • Example: $user[‘name’] is more meaningful than $user[0].

Flexible Data Storage:

  • They are ideal for storing data in key-value pairs, such as user information (name => John).

Simplifies Data Access:

  • You can directly access elements using a specific key instead of calculating an index.

Enhances Real-World Representation:

  • Associative arrays closely mimic structures like dictionaries or objects, which are common in real-world applications.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *