How can PDO be used to establish a connection to a database in PHP and execute SQL commands?
To establish a connection to a database and execute SQL commands in PHP, you can use PHP Data Objects (PDO). PDO provides a consistent interface for accessing databases, making it easier to work with different database systems. You can connect to a database by creating a new PDO object with the database's DSN (Data Source Name), username, and password. Once connected, you can prepare and execute SQL statements using PDO's prepared statements feature.
<?php
// Database credentials
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
// Create a new PDO instance
$pdo = new PDO($dsn, $username, $password);
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare and execute a SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
// Fetch the results
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Output the results
print_r($result);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>