How can the FETCH_KEY_PAIR method in PHP simplify the process of fetching data from a database?
The FETCH_KEY_PAIR method in PHP simplifies the process of fetching data from a database by retrieving key-value pairs directly, eliminating the need for additional processing to extract the desired data. This method can be especially useful when working with associative arrays or when needing to quickly access specific data points without iterating through a larger result set.
// Example of using FETCH_KEY_PAIR method to fetch data from a database
// Assuming $db is a PDO object connected to the database
$query = "SELECT id, name FROM users";
$stmt = $db->query($query);
// Fetching data as key-value pairs
$data = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
// Accessing the fetched data
foreach ($data as $id => $name) {
echo "User ID: $id, Name: $name <br>";
}