How can the DISTINCT keyword in SQL be used to retrieve unique categories from a table in PHP?
When using the DISTINCT keyword in SQL within a PHP script, you can retrieve unique categories from a table by selecting only distinct values in a specific column. This can be achieved by constructing a SQL query that includes the DISTINCT keyword followed by the column name from which you want to retrieve unique values. Once the query is executed, you can fetch the results and display the unique categories in your PHP application.
<?php
// Establish a connection to the 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);
}
// SQL query to retrieve unique categories from a table
$sql = "SELECT DISTINCT category FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Category: " . $row["category"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- How can PHP developers prevent overwriting existing data when using fopen() in PHP?
- Are there any specific PHP functions or methods that can simplify the handling of multidimensional arrays, particularly when dealing with nested arrays?
- What is the difference between HTTP and HTTPS headers in PHP authentication on SSL pages?