What advantages does using PDO::FETCH_KEY_PAIR offer when fetching data from a database in PHP?
When fetching data from a database in PHP, using PDO::FETCH_KEY_PAIR offers the advantage of returning an associative array where the key is one column from the result set and the value is another column. This can be particularly useful when you want to quickly access values from a database query using a specific identifier as the key.
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare and execute a query
$stmt = $pdo->prepare("SELECT id, name FROM users");
$stmt->execute();
// Fetch data as an associative array with id as key and name as value
$users = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
// Access data using the id as key
echo $users[1]; // Output: User1