How can PHP be integrated with MySQL to optimize server performance and resource utilization?

To optimize server performance and resource utilization when integrating PHP with MySQL, it is important to use prepared statements to prevent SQL injection attacks and improve query execution efficiency. Additionally, utilizing connection pooling and persistent connections can help reduce the overhead of establishing new database connections for each request.

// Establish a connection to the MySQL database using PDO with persistent connections
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

$options = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);

try {
    $pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

// Use prepared statements to execute queries safely and efficiently
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll();