Wednesday 11 July 2018

PHP PDO: Improve Performance with Persistent Connection

PHP PDO: Improve Performance with Persistent Connection

Persistent connections are known as way to improve performance. When a persistent connection is requested, PHP checks if there’s already an identical persistent connection from earlier remained open. If it exists, it uses it. What meaning of remained open? Persistent connection are links that do not close when the execution of your script ends. An ‘identical’ connection is a connection that was opened to the same host, with the same username and the same password.
How do use it at PDO? PDO have PDO::ATTR_PERSISTENT. We set in the PDO constructor:
<?php

// configuration

$dbhost        = "localhost";

$dbname        = "pdo";

$dbuser        = "root";

$dbpass        = "";

// database connection

$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass, array(PDO::ATTR_PERSISTENT => true));

// query

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT * FROM books";

$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo()));

$r = $q->fetch(PDO::FETCH_ASSOC);

print_r($r);

?>

0 comments:

Post a Comment