Skip to content
PHP Logo

How can one optimize PHP code for better performance when interacting with a MySQL database?

To optimize PHP code for better performance when interacting with a MySQL database, one should consider using prepared statements to prevent SQL injection attacks and reduce query parsing overhead. Additionally, using indexes on frequently queried columns can improve query performance. It is also beneficial to limit the data returned by queries to only what is necessary.

php
// Example of using prepared statements and limiting data returned by query
$stmt = $pdo->prepare("SELECT column1, column2 FROM table WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Process data here
}