How can PDO::FETCH_KEY_PAIR be utilized to retrieve data from a database and use it in PHP arrays?

To retrieve data from a database and use it in PHP arrays, you can utilize PDO::FETCH_KEY_PAIR fetch style in PDO. This fetch style fetches key-value pairs where the first column is the key and the second column is the value. This allows you to easily create associative arrays in PHP using data retrieved from the database.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query
$stmt = $pdo->prepare('SELECT id, name FROM users');

// Execute the query
$stmt->execute();

// Fetch key-value pairs into an associative array
$users = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// Output the result
print_r($users);