How can PHP beginners effectively structure their code for a gallery script that interacts with a MySQL database?

When creating a gallery script that interacts with a MySQL database, PHP beginners can effectively structure their code by separating concerns into different files or functions. They should create a database connection file, a file for retrieving images from the database, and a file for displaying the images in the gallery. By organizing their code in this way, beginners can easily maintain and update their gallery script in the future.

// database.php
<?php
$host = 'localhost';
$username = 'username';
$password = 'password';
$database = 'gallery';

$conn = new mysqli($host, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

// get_images.php
<?php
include 'database.php';

$sql = "SELECT * FROM images";
$result = $conn->query($sql);

$images = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $images[] = $row['image_path'];
    }
}
?>

// gallery.php
<?php
include 'get_images.php';

foreach ($images as $image) {
    echo '<img src="' . $image . '" alt="Gallery Image">';
}
?>