How can the use of fetch_assoc() in PHP help prevent duplicate data from being displayed in a foreach loop?
When using a foreach loop to display data from a MySQL database in PHP, the fetch_assoc() function can be used to fetch each row as an associative array. By using fetch_assoc() instead of fetch_array(), we can prevent duplicate data from being displayed in the loop because it only fetches the column values once. This ensures that each row is displayed only once in the loop.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Fetch data using fetch_assoc() to prevent duplicate data
$result = $conn->query("SELECT * FROM table");
while ($row = $result->fetch_assoc()) {
// Display data
echo $row['column_name'];
}
Keywords
Related Questions
- What are the potential drawbacks of implementing mail sending in the Model in PHP?
- How can PHP developers customize error messages for specific exceptions, such as integrity constraint violations, to provide more user-friendly feedback?
- Are there any best practices for troubleshooting JS problems in PHP applications?