How can PHP be used to generate a database output that lists each manufacturer only once?
To generate a database output that lists each manufacturer only once, we can use the DISTINCT keyword in the SQL query to retrieve unique manufacturer names. This ensures that each manufacturer is only displayed once in the output.
<?php
// 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 retrieve unique manufacturer names
$query = "SELECT DISTINCT manufacturer FROM products";
$result = $connection->query($query);
// Output the list of unique manufacturers
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["manufacturer"] . "<br>";
}
} else {
echo "No manufacturers found";
}
// Close connection
$connection->close();
?>
Keywords
Related Questions
- What are the benefits of using a template engine like Twig in PHP for generating dynamic content?
- What are the potential risks of using SELECT * in a PHP query and how can they be mitigated?
- What is the best practice for handling file attachments, specifically PDF files, using PHPMailer in PHP scripts?