How can the script be optimized to fetch data from the database more efficiently without calling mysql_fetch_array multiple times?

The issue can be solved by fetching all the data from the database at once using a single call to mysql_fetch_array. This can be achieved by fetching all the rows into an array and then iterating over that array to access individual rows. This reduces the number of calls to the database and improves efficiency.

// Connect to the database
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Query to fetch data from the database
$query = "SELECT * FROM table_name";
$result = mysqli_query($conn, $query);

// Fetch all rows into an array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Iterate over the array to access individual rows
foreach ($data as $row) {
    // Process each row as needed
}

// Free the result set and close the connection
mysqli_free_result($result);
mysqli_close($conn);