How can a beginner in PHP ensure they are following proper coding practices when counting unique entries in a column?

When counting unique entries in a column in PHP, a beginner should ensure they are following proper coding practices by using SQL queries with the DISTINCT keyword to retrieve unique values from the database column. They should also sanitize user input to prevent SQL injection attacks and use prepared statements to securely execute the SQL query.

<?php
// Establish a database connection
$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);
}

// Query to count unique entries in a column
$sql = "SELECT COUNT(DISTINCT column_name) AS unique_count FROM table_name";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output the unique count
    while($row = $result->fetch_assoc()) {
        echo "Unique count: " . $row["unique_count"];
    }
} else {
    echo "0 results";
}

$conn->close();
?>