How can one effectively retrieve data from a database and store it in an array in PHP?
To effectively retrieve data from a database and store it in an array in PHP, you can use the PDO extension to connect to the database, execute a query to fetch the data, and then loop through the results to store them in an array.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query
$stmt = $pdo->prepare("SELECT * FROM my_table");
// Execute the query
$stmt->execute();
// Fetch the results and store them in an array
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
// Print the array
print_r($data);
Keywords
Related Questions
- How can PHP form validation be improved to prevent the creation of a file if passwords do not match?
- How can the use of ternary operators in PHP code lead to parsing errors, and what are some best practices to avoid them?
- How can PHP developers effectively integrate HTML elements like frames into their projects?