What are the best practices for structuring and querying database tables to accurately count unique entries in PHP scripts?

When counting unique entries in database tables in PHP scripts, it's important to properly structure the tables and use the appropriate SQL queries to accurately count the unique entries. One common approach is to use the DISTINCT keyword in your SQL query to retrieve only unique values from a specific column. Additionally, you can use the COUNT() function in combination with GROUP BY to count the number of unique entries in a specific column.

// 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);
}

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

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

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Number of unique entries: " . $row["unique_count"];
    }
} else {
    echo "0 results";
}

$conn->close();