What is the best practice for handling dynamic content in PHP navigation systems?
When dealing with dynamic content in PHP navigation systems, the best practice is to use a database to store the navigation items and their corresponding URLs. This allows for easy updating and management of the navigation menu without having to modify the code each time a change is needed.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "navigation";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to fetch navigation items from database
$sql = "SELECT * FROM navigation_menu";
$result = $conn->query($sql);
// Display navigation menu
echo "<ul>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<li><a href='" . $row["url"] . "'>" . $row["name"] . "</a></li>";
}
} else {
echo "0 results";
}
echo "</ul>";
// Close connection
$conn->close();
?>