js

Thursday, December 7, 2023

Develop a PHP program to perform data insertion into the student table of a MySQL database. The student table contains columns such as name, roll_num, and class. The MySQL database is named student, and the connection details include a username of root and a password of password. Implement exception handling using try ... catch ... finally for any potential exceptions that may arise during the database operations

Q. Develop a PHP program to perform data insertion into the student table of a MySQL database. The student table contains columns such as name, roll_num, and class. The MySQL database is named studentDB, and the connection details include a username of root and a password of password. Implement exception handling using try ... catch ... finally for any potential exceptions that may arise during the database operations.

Solution:
<?php
// Database connection parameters
$host = 'localhost';  
$dbname = 'studentdb';
$username = 'root';
$password = 'password';

try {
    // Establish a database connection
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Sample data to insert
    $name = 'Gyaan Kunja';
    $rollNum = '1';
    $class = '10A';

    // Prepare the SQL statement
    $stmt = $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
    $pdo = null;
}

?>

No comments:

Post a Comment

SEBA HSLC Question Paper Assamese 2024