Home >headlines >pdo connection method in php

pdo connection method in php

无忌哥哥
无忌哥哥Original
2018-06-28 11:57:542579browse

* PDO connection data

* 1. PDO is the middle layer, or abstraction layer, between PHP and other databases

* 2. PDO shields the differences between databases. Provides a unified access interface to PHP

* 3. The first step in using PDO is to generate a PDO object. All functions must be called using this object

* 4. Success Return PDO object, failure throws exception

//1. Configuration parameters

* DNS: Data source

* Basic format: Database type: attribute 1: value 1; Attribute 2: Value 2;...

* Type: such as mysqli, oracle, etc.

* Attribute: host, default database, default character set, default port number

* For example: mysql:host=127.0.0.1;dbname=php;charset=utf8;port=3306;

$dsn = 'mysql:host=localhost; dbname=php; charset=utf8; port=3306';

//Database user name

$userName = 'root';

//Database user password

$password = 'root';

//Configure connection properties

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,  //设置错误模式
    PDO::ATTR_CASE => PDO::CASE_NATURAL,  //数据表字段保持不变
    PDO::ATTR_EMULATE_PREPARES => true, //启用PDO模拟
    PDO::ATTR_PERSISTENT => true, //启用持久性连接
];

//Use try-catch() to catch possible errors

try {
    //调用PDO构造函数实例化PDO类,创建PDO对象
    $pdo = new PDO($dsn, $userName, $password, $options);
    //连接是所有操作的基础,无论你设置的错误模式级别是什么,都会强制使用EXCEPTION异常模式
} catch (PDOException $e) {
    print 'Connect ERROR!:'.$e->getMessage(); //推荐使用英文提示,以防止页面中文乱码
    die();  //连接错误是致命错误,必须停止脚本的执行
}

//Disconnect PDO connection

$pdo = null;

//Destroy the PDO object

unset($pdo);

//More often, you can use the abbreviation:

$pdo = new PDO('mysql:dbname=php;','root', 'root'); //其它参数取默认值
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:update data in phpNext article:update data in php