PHP Lab Assignments for MCA Students
PHP Lab Assignments for MCA Students
A recursive function in PHP can calculate the Fibonacci sequence by calling itself with the adjusted parameters until it reaches a base case. In the Fibonacci sequence, each number is the sum of the two preceding ones. Thus, the recursive function makes two recursive calls subtracting one and two from the input until it reaches the first two base cases: 0 or 1. Here's a PHP implementation: ```php function fibonacci($n) { if ($n <= 0) { return 0; } else if ($n == 1) { return 1; } else { return fibonacci($n - 1) + fibonacci($n - 2); } } ``` For example, calling `fibonacci(5)` would calculate and return 5, as it recursively sums the Fibonacci values of preceding indices (3 and 2, etc.).
In PHP, class inheritance can be demonstrated by creating a superclass, 'Vehicle', and a subclass, 'Car'. The 'Vehicle' class would define properties and methods that are common to all vehicles. The 'Car' subclass extends 'Vehicle', allowing 'Car' to inherit those properties and methods. You can add specific methods and properties in 'Car' that are unique to cars. This relationship allows for code reusability and the implementation of polymorphic behavior. For example: ```php class Vehicle { protected $make; protected $model; public function __construct($make, $model) { $this->make = $make; $this->model = $model; } public function getMakeAndModel() { return $this->make . ' ' . $this->model; } } class Car extends Vehicle { private $year; public function __construct($make, $model, $year) { parent::__construct($make, $model); $this->year = $year; } public function displayInfo() { echo "Car: " . $this->getMakeAndModel() . ", Year: " . $this->year; } } $myCar = new Car('Toyota', 'Corolla', 2020); $myCar->displayInfo(); ``` This code snippet demonstrates how 'Car' inherits from 'Vehicle' and adds additional functionality, such as storing and displaying the year of the car .
Implementing CRUD operations on a MySQL database using PHP involves: 1. **Create:** Utilize an INSERT query to add new records to the database. ```php $sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')"; if ($pdo->exec($sql)) { echo "New record created successfully"; } ``` 2. **Read:** Execute a SELECT query to fetch records from the database. ```php $stmt = $pdo->query("SELECT * FROM table_name"); while ($row = $stmt->fetch()) { echo $row['column_name']; } ``` 3. **Update:** Use an UPDATE query to modify existing records. ```php $sql = "UPDATE table_name SET column1 = 'value' WHERE condition"; $stmt = $pdo->prepare($sql); $stmt->execute(); ``` 4. **Delete:** Perform a DELETE query to remove records. ```php $sql = "DELETE FROM table_name WHERE condition"; $stmt = $pdo->prepare($sql); $stmt->execute(); ``` Each step requires secure database handling with prepared statements to avoid SQL injection, proper error checking, and resource management .
Validating an email address in PHP can be efficiently achieved using PHP's filter_var() function with the FILTER_VALIDATE_EMAIL flag. This built-in function checks whether a given email address meets the standard email format. Here is a demonstration: ```php $email = "example@example.com"; if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Email is valid."; } else { echo "Email is not valid."; } ``` filter_var() returns the sanitized email if it is valid according to the specified filter or FALSE if it is not, providing a simple yet effective way to ensure the email adheres to standard formatting rules .
Exception handling in PHP involves using try-catch blocks to manage errors gracefully. The process involves the following steps: 1. Write a try block where the code that may cause an exception is placed. 2. Throw an exception within the try block using `throw` if a specific condition is met or an error is encountered. 3. Use a catch block immediately following the try block to catch the thrown exception. The catch block can include specific exception types if needed. 4. Handle the exception within the catch block by taking corrective actions or logging the error. Here's an example: ```php try { // Code that may throw an exception if(!$dbConnection) { throw new Exception('Database connection failed.'); } } catch(Exception $e) { // Handle exception echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` This example demonstrates how to check for a failed database connection and handle the exception by displaying an error message .
When connecting to and interacting with a MySQL database using PHP, several considerations are critical to ensure secure and efficient operations: 1. **Security:** Use prepared statements and parameterized queries to prevent SQL injection attacks. 2. **Error Handling:** Implement robust error handling using try-catch blocks to manage exceptions like connection failures. 3. **Database Credentials:** Store sensitive credentials securely and use environment variables or configuration files to manage them. 4. **Connection Management:** Properly open and close database connections to manage resources efficiently and avoid memory leaks. 5. **Compatibility:** Use the `PDO` extension or `MySQLi` for database interactions as they offer both procedural and object-oriented interfaces. Sample code for connecting to a MySQL database using PDO: ```php try { $pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ``` This example demonstrates using a secure and efficient method (PDO) for connecting to a database, while handling exceptions if the connection fails .
The while loop in PHP allows repeated execution of a block of code as long as a specified condition is true. Here are two tasks demonstrating its use: **Printing even numbers from 1 to 20:** ```php $i = 1; while ($i <= 20) { if ($i % 2 == 0) { echo $i . " "; } $i++; } ``` This loop iterates through numbers from 1 to 20, checking if a number is even using the modulus operator, and prints it if true. **Calculating the sum of digits of a number:** ```php $number = 1234; $sum = 0; while ($number != 0) { $sum += $number % 10; $number = (int)($number / 10); } echo "Sum of digits: $sum"; ``` This script calculates the sum of digits by repeatedly taking the last digit using modulus and reducing the number using division, demonstrating effective use of the while loop for mathematical operations .
Creating a class with a constructor and a destructor in PHP involves defining these methods in the class. The constructor method, __construct(), is automatically called when an object is created, and the destructor method, __destruct(), is called when an object is destroyed or script execution ends. Here's how you can implement it with a Person class: ```php class Person { private $name; private $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; echo "A new person named {$this->name} has been created.\n"; } public function __destruct() { echo "The person named {$this->name} is being destroyed.\n"; } } $person = new Person("John Doe", 30); ``` In this example, when an object of Person is created, the constructor initializes the object's properties, and upon script termination, the destructor outputs a message indicating destruction .
File handling in PHP involves using built-in functions to open, write, read, and close files. To create a file and write text into it, use fopen(), fwrite(), and fclose(). To read the content, use fopen(), fread(), and fclose(). **Creating and writing to a file:** ```php $file = fopen('myfile.txt', 'w'); if ($file) { fwrite($file, "Hello, this is a test text."); fclose($file); } else { echo "Unable to open or create the file."; } ``` This script opens 'myfile.txt' for writing, writes a line of text, and then closes the file. **Reading from a file:** ```php $file = fopen('myfile.txt', 'r'); if ($file) { $content = fread($file, filesize('myfile.txt')); echo "File Content: $content"; fclose($file); } else { echo "Unable to open the file."; } ``` This second script opens the same file in read mode, reads its contents, and then displays it, completing the file handling cycle .
Associative arrays in PHP allow the use of named keys to index values, providing a way to map meaningful keys to their respective values. They can be utilized for data association, where the key acts as an identifier, making it easier to manage and access data. To search for a specific value, you can use `array_search()`, which returns the key if the value is found. Example: ```php $students = array("John" => 85, "Jane" => 92, "Dave" => 78); $searchFor = 92; $key = array_search($searchFor, $students); if ($key !== false) { echo "Found: $key with grade $searchFor"; } else { echo "Value not found in the array."; } ``` This code searches for a grade in the array and returns the student's name if the grade is found, demonstrating the utility of associative arrays for mapping data .