Q. Write a PHP program that uses a class and object to insert data into the student table of a MySQL database. The student table has columns name, roll_num, and class. The MySQL database connection details are as follows: host is localhost, database name is student, username is root, and password is password. Implement exception handling using try ... catch for any potential exceptions during database operations.
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();
}
}
public function __destruct() {
// Close the database connection in the destructor
$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