What SQL statement can be used to retrieve distinct values from a column in a database table?
To retrieve distinct values from a column in a database table, you can use the SQL SELECT DISTINCT statement. This statement allows you to fetch unique values from a specific column in a table. By using this statement, you can eliminate duplicate values and only retrieve distinct values from the specified column.
<?php
// Connect 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 distinct values from a column
$sql = "SELECT DISTINCT column_name FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column Value: " . $row["column_name"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are some best practices for handling exceptions and error messages in PHP database operations to effectively debug and resolve issues with query execution?
- What potential pitfalls should be considered when dealing with unsanctioned 404 tricks in PHP scripts?
- What are the advantages of using PDO or MySQLi over the deprecated MySQL component in PHP for database interactions in this scenario?