Q. Create a PHP script with a class that encapsulates the database operations. The class should have methods for establishing a database connection, inserting data into the student table, and closing the connection. Utilize the try ... catch ... finally construct to handle exceptions gracefully.
Solution
<?php
class StudentDatabase {
private $pdo;
public function __construct($host, $dbname, $username, $password) {
try {
// Establish a database connection
$this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// Set the PDO error mode to exception
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
public function insertStudent($name, $rollNum, $class) {
try {
// Prepare the SQL statement
$stmt = $this->pdo->prepare("INSERT INTO student (name, roll_num, class) VALUES (:name, :roll_num, :class)");
// Bind parameters
$stmt->bindParam(':name', $name);
$stmt->bindParam(':roll_num', $rollNum);
$stmt->bindParam(':class', $class);
// Execute the statement
$stmt->execute();
echo "Data inserted successfully!";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
} finally {
// Close the database connection in the finally block
$this->closeConnection();
}
}
private function closeConnection() {
// Close the database connection
$this->pdo = null;
}
}
// Database connection parameters
$host = 'localhost'; // Change to your database host
$dbname = 'student';
$username = 'root';
$password = 'password';
// Create an instance of the StudentDatabase class
$studentDb = new StudentDatabase($host, $dbname, $username, $password);
// Sample data to insert
$name = 'Gyaan kunja';
$rollNum = '1';
$class = '10A';
// Call the insertStudent method using the object
$studentDb->insertStudent($name, $rollNum, $class);
?>
No comments:
Post a Comment