What are the best practices for handling and manipulating data retrieved from a MySQL database in PHP to ensure accurate and efficient processing?

When handling and manipulating data retrieved from a MySQL database in PHP, it is important to sanitize input data to prevent SQL injection attacks and ensure data integrity. Use prepared statements or parameterized queries to safely interact with the database. Additionally, properly handle errors and exceptions to maintain data accuracy and efficiency.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Sanitize input data
$id = mysqli_real_escape_string($mysqli, $_GET['id']);

// Prepare and execute a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

// Fetch data and process it
while ($row = $result->fetch_assoc()) {
    // Manipulate data as needed
}

// Close statement and connection
$stmt->close();
$mysqli->close();