Interview question
How do you connect to a MySQL database using PDO? PDO का उपयोग करके MySQL database से कैसे connect करें?
Answer
Create a new PDO instance with a DSN (Data Source Name), username, password, and options. Always wrap it in try-catch since PDO throws exceptions on connection failure.
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
'username',
'password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}Setting ERRMODE_EXCEPTION ensures database errors throw catchable exceptions instead of silent failures.
PDO instance को DSN, username, password के साथ बनाएं। हमेशा try-catch में wrap करें क्योंकि connection fail होने पर PDO exception throw करता है।
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
'username',
'password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}Was this answer clear?