What are potential pitfalls when trying to store data from a database in an array in PHP?

When storing data from a database in an array in PHP, potential pitfalls include not properly handling errors such as database connection failures or query errors, not sanitizing input to prevent SQL injection attacks, and not properly looping through the result set. To solve these issues, make sure to check for errors, sanitize input using prepared statements, and iterate through the result set correctly.

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

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

// Prepare and execute query
$query = "SELECT * FROM table";
$result = $connection->query($query);

// Check for query errors
if (!$result) {
    die("Query failed: " . $connection->error);
}

// Fetch data and store in an array
$data = array();
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

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

// Use the $data array as needed