How can the issue of data duplication be addressed when working with multiple entries in a database query result in PHP?
Issue: Data duplication can be addressed by using the DISTINCT keyword in the SQL query to ensure that only unique entries are returned in the result set. PHP Code Snippet:
<?php
// Connect to 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 with DISTINCT keyword to avoid data duplication
$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 Name: " . $row["column_name"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- What are some common mistakes to avoid when working with PHP and MySQL interactions in a web development project?
- How can PHP be used to dynamically generate content for headers and footers on web pages?
- What are some best practices for efficiently incorporating maps or graphics into a website using PHP?