Php function pdo connection

PHP Data Objects

This is a little late. but I’m old and slow.
Regarding Extending PDOStatement and PDO I found that sending the PDOExtended class by reference helps:
In the constructor after parent::__construct() :
$this->setAttribute(\PDO::ATTR_STATEMENT_CLASS,array(‘PDOStatementExtended’, [&$this]));>

And in
class PDOStatementExtended extends \PDOStatement

protected function __construct
(
\PDO &$PDO,
)

I wanted to extend PDO class to store statistics of DB usage, and I faced some problems. I wanted to count number of created statements and number of their executings. So PDOStatement should have link to PDO that created it and stores the statistical info. The problem was that I didn’t knew how PDO creates PDOStatement (constructor parameters and so on), so I have created these two classes:

/**
* PHP Document Object plus
*
* PHP Document Object plus is library with functionality of PDO, entirely written
* in PHP, so that developer can easily extend it’s classes with specific functionality,
* such as providing database usage statistics implemented in v1.0b
*
* @author Peter Pokojny
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
class PDOp protected $PDO ;
public $numExecutes ;
public $numStatements ;
public function __construct ( $dsn , $user = NULL , $pass = NULL , $driver_options = NULL ) $this -> PDO = new PDO ( $dsn , $user , $pass , $driver_options );
$this -> numExecutes = 0 ;
$this -> numStatements = 0 ;
>
public function __call ( $func , $args ) return call_user_func_array (array(& $this -> PDO , $func ), $args );
>
public function prepare () $this -> numStatements ++;

$args = func_get_args ();
$PDOS = call_user_func_array (array(& $this -> PDO , ‘prepare’ ), $args );

return new PDOpStatement ( $this , $PDOS );
>
public function query () $this -> numExecutes ++;
$this -> numStatements ++;

Читайте также:  Javascript datetime to integer

$args = func_get_args ();
$PDOS = call_user_func_array (array(& $this -> PDO , ‘query’ ), $args );

return new PDOpStatement ( $this , $PDOS );
>
public function exec () $this -> numExecutes ++;

$args = func_get_args ();
return call_user_func_array (array(& $this -> PDO , ‘exec’ ), $args );
>
>
class PDOpStatement implements IteratorAggregate protected $PDOS ;
protected $PDOp ;
public function __construct ( $PDOp , $PDOS ) $this -> PDOp = $PDOp ;
$this -> PDOS = $PDOS ;
>
public function __call ( $func , $args ) return call_user_func_array (array(& $this -> PDOS , $func ), $args );
>
public function bindColumn ( $column , & $param , $type = NULL ) if ( $type === NULL )
$this -> PDOS -> bindColumn ( $column , $param );
else
$this -> PDOS -> bindColumn ( $column , $param , $type );
>
public function bindParam ( $column , & $param , $type = NULL ) if ( $type === NULL )
$this -> PDOS -> bindParam ( $column , $param );
else
$this -> PDOS -> bindParam ( $column , $param , $type );
>
public function execute () $this -> PDOp -> numExecutes ++;
$args = func_get_args ();
return call_user_func_array (array(& $this -> PDOS , ‘execute’ ), $args );
>
public function __get ( $property ) return $this -> PDOS -> $property ;
>
public function getIterator () return $this -> PDOS ;
>
>
?>

Classes have properties with original PDO and PDOStatement objects, which are providing the functionality to PDOp and PDOpStatement.
From outside, PDOp and PDOpStatement look like PDO and PDOStatement, but also are providing wanted info.

When using prepared statements there is no official PDO feature to show you the final query string that is submitted to a database complete with the parameters you passed.

Use this simple function for debugging. The values you are passing may not be what you expect.

//Sample query string
$query = «UPDATE users SET name = :user_name WHERE > ;

//Sample parameters
$params = [ ‘:user_name’ => ‘foobear’ , ‘:user_id’ => 1001 ];

function build_pdo_query ( $string , $array ) //Get the key lengths for each of the array elements.
$keys = array_map ( ‘strlen’ , array_keys ( $array ));

//Sort the array by string length so the longest strings are replaced first.
array_multisort ( $keys , SORT_DESC , $array );

foreach( $array as $k => $v ) //Quote non-numeric values.
$replacement = is_numeric ( $v ) ? $v : «‘ < $v >‘» ;

//Replace the needle.
$string = str_replace ( $k , $replacement , $string );
>

echo build_pdo_query ( $query , $params ); //UPDATE users SET name = ‘foobear’ WHERE/> ?>

Источник

Подключения и управление подключениями

Соединения устанавливаются автоматически при создании объекта PDO от его базового класса. Не имеет значения, какой драйвер вы хотите использовать; вы всегда используете имя базового класса. Конструктор класса принимает аргументы для задания источника данных (DSN), а также необязательные имя пользователя и пароль (если есть).

Пример #1 Подключение к MySQL

В случае возникновения ошибки при подключении будет выброшено исключение PDOException . Его можно перехватить и обработать, либо оставить на откуп глобальному обработчику ошибок, который вы задали функцией set_exception_handler() .

Пример #2 Обработка ошибок подключения

try $dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
foreach( $dbh -> query ( ‘SELECT * from FOO’ ) as $row ) print_r ( $row );
>
$dbh = null ;
> catch ( PDOException $e ) print «Error!: » . $e -> getMessage () . «
» ;
die();
>
?>

Если ваше приложение не перехватывает исключение PDO конструктора, движок zend выполнит стандартные операции для завершения работы скрипта и вывода обратной трассировки. В этой трассировке будет содержаться детальная информация о соединении с базой данных, включая имя пользователя и пароль. Ответственность за перехват исключений лежит на вас. Перехватить исключение можно явно (с помощью выражения catch ), либо неявно, задав глобальный обработчик ошибок функцией set_exception_handler() .

При успешном подключении к базе данных в скрипт будет возвращён созданный объект PDO. Соединение остаётся активным на протяжении всего времени жизни объекта. Чтобы закрыть соединение, необходимо уничтожить объект путём удаления всех ссылок на него (этого можно добиться, присваивая null всем переменным, указывающим на объект). Если не сделать этого явно, PHP автоматически закроет соединение по окончании работы скрипта.

Замечание: Если существуют другие ссылки на данный экземпляр PDO (например, из объекта PDOStatement или другие переменные, ссылающиеся на него), они также должны быть удалены (например, присвоением null переменной, ссылающейся на PDOStatement).

Пример #3 Закрытие соединения

$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
// здесь мы каким-то образом используем соединение
$sth = $dbh -> query ( ‘SELECT * FROM foo’ );

// соединение больше не нужно, закрываем
$sth = null ;
$dbh = null ;
?>

Во многих приложениях может оказаться полезным использование постоянных соединений к базам данных. Постоянные соединения не закрываются при завершении работы скрипта, они кешируются и используются повторно, когда другой скрипт запрашивает соединение с теми же учётными данными. Постоянные соединения позволяют избежать создания новых подключений каждый раз, когда требуется обмен данными с базой, что в результате даёт прирост скорости работы таких приложений.

Пример #4 Постоянные соединения

$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass , array(
PDO :: ATTR_PERSISTENT => true
));
?>

Значение параметра PDO::ATTR_PERSISTENT преобразуется в логическое значение ( bool ) (включить/отключить постоянные подключения), если это не числовая строка ( string ), которая в этом случае позволяет использовать несколько пулов постоянных подключений. Это полезно, если разные соединения используют несовместимые настройки, например, разные значения PDO::MYSQL_ATTR_USE_BUFFERED_QUERY .

Замечание:

Чтобы использовать постоянные соединения, необходимо добавить константу PDO::ATTR_PERSISTENT в массив параметров драйвера, который передаётся конструктору PDO. Если просто задать этот атрибут функцией PDO::setAttribute() уже после создания объекта, драйвер не будет использовать постоянные соединения.

Замечание:

Если вы используете PDO ODBC драйвер и ваши ODBC библиотеки поддерживают объединение подключений в пул (ODBC Connection Pooling) (unixODBC и Windows точно поддерживают, но могут быть и другие), то рекомендуется вместо постоянных соединений пользоваться этим пулом. Пул подключений ODBC доступен всем модулям текущего процесса; если PDO сам кеширует соединение, то это соединение будет недоступно другим модулям и не попадёт в пул. В результате каждый модуль будет создавать дополнительные подключения для своих нужд.

User Contributed Notes

  • PDO
    • Введение
    • Установка и настройка
    • Предопределённые константы
    • Подключения и управление подключениями
    • Транзакции и автоматическая фиксация изменений
    • Подготовленные запросы и хранимые процедуры
    • Ошибки и их обработка
    • Большие объекты (LOB)
    • PDO
    • PDOStatement
    • PDOException
    • Драйверы PDO

    Источник

    PDO::__construct

    Creates a PDO instance to represent a connection to the requested database.

    Parameters

    The Data Source Name, or DSN, contains the information required to connect to the database.

    In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

    The dsn parameter supports three different methods of specifying the arguments required to create a database connection:

    dsn contains the full DSN.

    dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

    uri:file:///path/to/dsnfile

    dsn consists of a name name that maps to pdo.dsn. name in php.ini defining the DSN string.

    Note:

    The alias must be defined in php.ini , and not .htaccess or httpd.conf

    The user name for the DSN string. This parameter is optional for some PDO drivers.

    The password for the DSN string. This parameter is optional for some PDO drivers.

    A key=>value array of driver-specific connection options.

    Errors/Exceptions

    PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails, regardless of which PDO::ATTR_ERRMODE is currently set.

    Examples

    Example #1 Create a PDO instance via driver invocation

    /* Connect to a MySQL database using driver invocation */
    $dsn = ‘mysql:dbname=testdb;host=127.0.0.1’ ;
    $user = ‘dbuser’ ;
    $password = ‘dbpass’ ;

    $dbh = new PDO ( $dsn , $user , $password );

    Example #2 Create a PDO instance via URI invocation

    The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

    odbc:DSN=SAMPLE;UID=john;PWD=mypass

    The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:

    /* Connect to an ODBC database using driver invocation */
    $dsn = ‘uri:file:///usr/local/dbconnect’ ;
    $user = » ;
    $password = » ;

    $dbh = new PDO ( $dsn , $user , $password );

    Example #3 Create a PDO instance using an alias

    The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb :

    [PDO] pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"

    /* Connect to an ODBC database using an alias */
    $dsn = ‘mydb’ ;
    $user = » ;
    $password = » ;

    $dbh = new PDO ( $dsn , $user , $password );

    Источник

Оцените статью