How can PHP developers effectively remove \n and \r characters from data fields in a MySQL database?

To effectively remove \n and \r characters from data fields in a MySQL database, PHP developers can use the str_replace function to replace these characters with an empty string. By running this function on the data before inserting or updating it in the database, the unwanted characters can be removed.

// Fetch data from the database
$data = $row['data'];

// Remove \n and \r characters
$data = str_replace(array("\n", "\r"), '', $data);

// Update the data in the database
$query = "UPDATE table SET data = '$data' WHERE id = $id";
$result = mysqli_query($connection, $query);

if ($result) {
    echo "Data updated successfully!";
} else {
    echo "Error updating data: " . mysqli_error($connection);
}