How can PDO be utilized to fetch data from SQL tables and create arrays in PHP?
To fetch data from SQL tables and create arrays in PHP using PDO, you can execute a SELECT query to retrieve the data and then loop through the results to build an array. This array can then be used for further processing or display.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare and execute the SELECT query
$stmt = $pdo->query('SELECT * FROM my_table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Create an array to store the fetched data
$dataArray = array();
foreach ($results as $row) {
$dataArray[] = $row;
}
// Display the fetched data
print_r($dataArray);
?>
Keywords
Related Questions
- What are the potential pitfalls of using htmlentities() in PHP, especially when dealing with HTML tags and special characters?
- What potential pitfalls can arise when managing user comments in a PHP application, especially in terms of tracking responses and user interactions?
- What best practices should be followed when constructing email headers in PHP?