Home> headlines> body text

pdo connection method in php

无忌哥哥
Release: 2018-06-28 11:57:54
Original
2495 people have browsed it

* 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';
Copy after login

//Database user name

$userName = 'root';
Copy after login

//Database user password

$password = 'root';
Copy after login

//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, //启用持久性连接 ];
Copy after login

//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(); //连接错误是致命错误,必须停止脚本的执行 }
Copy after login

//Disconnect PDO connection

$pdo = null;
Copy after login

//Destroy the PDO object

unset($pdo);
Copy after login

//More often, you can use the abbreviation:

$pdo = new PDO('mysql:dbname=php;','root', 'root'); //其它参数取默认值
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!