How can PHP be used to retrieve and display multiple categories associated with a single article from a relational database?
To retrieve and display multiple categories associated with a single article from a relational database, you can use SQL queries to fetch the relevant data and then use PHP to display it on the webpage. You can use JOIN statements to link the article and category tables based on their relationship, and then fetch and display the category names associated with the article.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Query to retrieve article and its associated categories
$stmt = $pdo->prepare('SELECT articles.title, categories.name
FROM articles
JOIN article_category ON articles.id = article_category.article_id
JOIN categories ON article_category.category_id = categories.id
WHERE articles.id = :article_id');
$stmt->execute(['article_id' => $article_id]);
// Display the article title
echo "<h1>{$article_title}</h1>";
// Display the categories associated with the article
echo "<ul>";
while ($row = $stmt->fetch()) {
echo "<li>{$row['name']}</li>";
}
echo "</ul>";
?>
Related Questions
- In what situations would it be more appropriate to use files instead of sessions for storing data in a PHP application?
- What are best practices for managing paths and directories in PHP scripts within a CMS?
- How can the PHP code for processing form submissions be optimized to correctly interpret Umlaut characters?