PDO (PHP Data Objects) is a PHP extension providing a uniform method of access to multiple databases. It's a secure and efficient way to connect to databases like MySQL, PostgreSQL, SQLite, etc. Here's a step-by-step guide on how to connect to MySQL using PDO in PHP:
<?php
$host = 'localhost'; // MySQL host
$dbname = 'your_database'; // Database name
$username = 'your_username'; // MySQL username
$password = 'your_password'; // MySQL password
try {
// Connect to MySQL using PDO
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// Set PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully<br>";
// Perform a sample query
$stmt = $pdo->prepare("SELECT * FROM your_table");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Displaying results
if (count($result) > 0) {
echo "Results:<br>";
foreach ($result as $row) {
echo "ID: " . $row['id'] . ", Name: " . $row['name'] . "<br>";
}
} else {
echo "No records found";
}
// Close the connection
$pdo = null;
} catch(PDOException $e) {
// Display connection error
echo "Connection failed: " . $e->getMessage();
}
?>