How can a developer ensure that a menu in a PHP application only displays unique categories from a database table?
To ensure that a menu in a PHP application only displays unique categories from a database table, the developer can use the DISTINCT keyword in the SQL query to fetch only unique values. By using the DISTINCT keyword, duplicate categories will be eliminated, and only unique categories will be displayed in the menu.
// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Query to fetch unique categories
$sql = "SELECT DISTINCT category FROM categories_table";
$result = $connection->query($sql);
// Display unique categories in the menu
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<a href='#'>" . $row['category'] . "</a><br>";
}
} else {
echo "No categories found";
}
// Close connection
$connection->close();
Keywords
Related Questions
- How can a PHP developer effectively handle the replacement of variables in an HTML template using a template engine, and what are some recommended template engine options for this task?
- What are the pros and cons of using static versus dynamic linking of categories and articles in a PHP-based marketplace script?
- How can PHP classes be used to store and manipulate arrays effectively?