0% found this document useful (0 votes)
7 views3 pages

PHP Lab Assignments for MCA Students

The document outlines the practical assignments for the Web Development using PHP Lab for the Master of Computer Application program, Batch 2024-2027. It includes general instructions for submission and a list of 25 PHP programming tasks that students must complete. Assignments must be handwritten, submitted in a specific format, and adhere to deadlines to avoid penalties for discrepancies.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

PHP Lab Assignments for MCA Students

The document outlines the practical assignments for the Web Development using PHP Lab for the Master of Computer Application program, Batch 2024-2027. It includes general instructions for submission and a list of 25 PHP programming tasks that students must complete. Assignments must be handwritten, submitted in a specific format, and adhere to deadlines to avoid penalties for discrepancies.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SCHOOL OF ENGINEERING & IT

DEPARTMENT OF COMPUTER SCIENCE & IT


MASTER OF COMPUTER APPLICATION
BATCH 2024 - 2027

SEMESTER II – A
WEB DEVELOPMENT USING PHP LAB

SESSION 2024-25

PRACTICAL ASSIGNMENTS

Prepared By:
RAJESH KUMAR GUPTA
Assistant Professor
General Instructions
1. Students are advised to submit the assignment along with the below-mentioned information at
the top Page: -
I. Student ID : - AJU/210XXX
II. Name of The Students :-
III. Course Name :-
IV. Contact No :-
V. E-Mail :-
2. Total of 5 assignments will be given. All the Assignments are compulsory
3. Submit unit-wise Assignment.
4. Each Assignment has a separate deadline.
5. Assignment correction should be on or before the deadline.
6. Students have to use only Classmate Type Copy to Answer their Assignment in their own
handwriting.
7. Typed or Print out Assignments are not accepted.
8. After completing the assignment, the student will make a scanned copy of the solution in pdf
format and afterward has to submit by google form or via mail only.
9. The Assignment pdf file name would be in the unique format of Students Registan no +
Course Code. (Ex: - AJU/210001 and CSC10023 pdf file name should be
AJU_210001_CSC10023).
10. If any discrepancy such as copying/duplication from others is found in the assignment
submitted, cancellation of the entire assignment may be imposed.
11. Students should have to retain hand written hard copy of the Assignments Sent for future
reference as well as submission to the course teacher as instructed.
ASSIGNMENT

1. Write a PHP script to print "Hello, World!" on the browser.


2. Write a PHP program to check if a given number is even or odd.
3. Write a PHP script to find the largest of three numbers using if-else.
4. Write a PHP program that prints numbers from 1 to 100 using a for loop.
5. Create a while loop that prints even numbers from 1 to 20.
6. Write a PHP script that uses a switch statement to display the day of the week based on a
number (1–7).
7. Write a program to calculate the sum of digits of a number using a while loop.
8. Write a PHP script to search for a specific value in an array.
9. Write a PHP program to sort an array in ascending and descending order.
10. Write a PHP script to count the number of words in a string.
11. Write a PHP script to create a form that accepts a user’s name and displays a greeting
message.
12. Write a script that validates an email address.
13. Write a PHP function to find the factorial of a number.
14. Write a PHP function that takes two arguments and returns their sum.
15. Write a recursive function to calculate the Fibonacci sequence.
16. Define a class Car with properties brand, model, and year. Create an object and display its
details.
17. Write a PHP program to implement inheritance with a Vehicle class and a Car subclass.
18. Create a Person class with a constructor and a destructor.
19. Write a PHP script to connect to a MySQL database.
20. Write a PHP script to insert data into a MySQL table.
21. Write a PHP script to fetch and display records from a MySQL table.
22. Write a PHP script to update and delete records in a MySQL table.
23. Write a PHP script that uses try-catch to handle exceptions.
24. Write a PHP program to create a file and write some text into it.
25. Write a PHP script to read data from a file and display it.

Common questions

Powered by AI

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 .

You might also like