What are some best practices for handling data retrieval and manipulation in PHP when working with MySQL databases?

When working with MySQL databases in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Additionally, it is recommended to fetch data in chunks rather than all at once to optimize performance and reduce memory usage. Finally, always sanitize user input before using it in database queries to avoid potential vulnerabilities.

// Example of using prepared statements to retrieve and manipulate data from a MySQL database

// Establish a connection to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a statement to retrieve data
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind parameters and execute the query
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();

// Fetch data in chunks and process each row
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Manipulate the data as needed
    echo $row['username'] . "<br>";
}

// Close the connection
$pdo = null;