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
- How can the defined constants for file paths be accessed and used in different parts of a PHP script or project?
- Are there any recommended resources or tools for easier PHP installation for beginners?
- How can PHP developers troubleshoot and debug unexpected T_VARIABLE errors in their code when constructing SQL queries?