How can PHP arrays be dynamically populated with data from SQL queries?
To dynamically populate PHP arrays with data from SQL queries, you can use the mysqli extension to connect to a database, execute a query, and fetch the results into an array. You can then loop through the fetched data and populate your PHP array accordingly.
<?php
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute a SQL query
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
// Populate PHP array with fetched data
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
// Close connection
$mysqli->close();
// Print the populated array
print_r($data);
?>
Keywords
Related Questions
- What potential errors or pitfalls can arise when using multiple instances of a specific string in a PHP function like str_replace?
- Are there any best practices for handling email headers, such as the "From" field, in PHP scripts?
- What could be the reason for a PHP code working well in IE but not in FF when setting cookies?