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);
Keywords
Related Questions
- What is the difference between substr() and mb_substr() in PHP, and when should each be used?
- Can anyone recommend a script or approach for handling input/output from MySQL in PHP that is optimized for server speed?
- What are the potential drawbacks of saving PHP echo outputs directly to a text file?