How can PHP be used to list all articles from a MySQL database and assign them to projects?

To list all articles from a MySQL database and assign them to projects, we can use PHP to retrieve the articles from the database and then assign them to the respective projects based on certain criteria such as project ID or category. This can be achieved by querying the database for the articles and then organizing them into an array or object structure that includes the project assignments.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Query to retrieve articles from database
$sql = "SELECT * FROM articles";
$result = $conn->query($sql);

// Assign articles to projects based on criteria
$projects = [];
while ($row = $result->fetch_assoc()) {
    $article = $row['article_title'];
    $project_id = $row['project_id'];

    if (!isset($projects[$project_id])) {
        $projects[$project_id] = [];
    }

    $projects[$project_id][] = $article;
}

// Display the projects and their assigned articles
foreach ($projects as $project_id => $articles) {
    echo "Project ID: " . $project_id . "<br>";
    echo "Articles: <br>";
    foreach ($articles as $article) {
        echo "- " . $article . "<br>";
    }
    echo "<br>";
}

// Close MySQL connection
$conn->close();
?>