Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created November 26, 2013 09:35
Show Gist options
  • Select an option

  • Save umidjons/7655702 to your computer and use it in GitHub Desktop.

Select an option

Save umidjons/7655702 to your computer and use it in GitHub Desktop.
PHP: Persistent connection to DB via PDO / use existing connection if available.
<?php
class MyClass
{
const DB_HOST = '127.0.0.1';
const DB_NAME = 'mydb';
const DB_USER = 'me';
const DB_PSWD = '123abc';
private static $db;
protected static function conn()
{
$opts = array(
PDO::ATTR_PERSISTENT => true, // use existing connection if exists, otherwise try to connect
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC // by default fetch results as associative array
);
self::$db = new PDO( sprintf( "mysql:host=%s;dbname=%s;charset=utf8", self::DB_HOST, self::DB_NAME ), self::DB_USER, self::DB_PSWD, $opts );
return self::$db;
}
public static function example()
{
$results = self::conn()->query( "SELECT * FROM my_table" );
echo '<pre>' . print_r( $results, true ) . '</pre>';
}
}
// Entry point:
MyClass::example();
@moses-gangipogu
Copy link

hi try the same i am getting too many connection error . so how could i test that my persistant connection is actually working.. means how to get to know that actually connection are been reused

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment