What is the best practice for populating an associative array from a MySQL table in PHP?

When populating an associative array from a MySQL table in PHP, it is best practice to fetch the data from the database using a query and then iterate over the results to populate the array. You can use the fetch_assoc() function to retrieve each row as an associative array where the column names are the keys. This allows you to easily access the data using the column names as keys in the array.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Query to select data from the table
$query = "SELECT * FROM table_name";
$result = $mysqli->query($query);

// Initialize an empty associative array
$data = array();

// Loop through the results and populate the associative array
while ($row = $result->fetch_assoc()) {
    $data[$row['column_name']] = $row['column_value'];
}

// Close the connection
$mysqli->close();

// Use the $data array as needed