Skip to content
PHP Logo

How can PHP developers utilize array_chunk() to organize data from a MySQL database for efficient display?

When displaying a large amount of data from a MySQL database, it can be overwhelming for users to see everything at once. By using the array_chunk() function in PHP, developers can organize the data into smaller chunks or pages, making it easier for users to navigate and digest the information. This can improve the efficiency of displaying data and enhance the user experience.

php
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

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

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

// Chunk the data into smaller arrays with 10 items each
$chunks = array_chunk($data, 10);

// Display the first chunk of data
foreach ($chunks[0] as $row) {
    echo $row['column_name1'] . " - " . $row['column_name2'] . "<br>";
}
?>