Home Database Mysql Tutorial Call constructors in various ways to create PDO objects

Call constructors in various ways to create PDO objects

May 20, 2017 pm 05:19 PM

Call the constructor in a variety of ways to create a PDO object

The constructor can be called in a variety of ways to create a PDO object. The following is to connect MySQL and Oracle. Taking the server as an example, we will introduce the various calling methods of the construction method.

1. Embed parameters into the constructor

In the following example of connecting to the Oracle server, load the OCI driver in the DSN string The program also specifies two optional parameters: the first is the database name, and the second is the character set. Use a specific character set to connect to a specific database. If no information is specified, the default database will be used. The code is as follows:

<?php
try{
    $dbh = new PDO("OCI:dbname = accounts;charset=UTF8","scott","tiger");
}catch (PDOException $e){
    echo "数据库连接失败:".$e->getMessage();
}
?>
Copy after login

OCI:dbname=accounts tells PDO that it should use the OCI driver, and that the "accounts" database should be used. For the MySQL driver, everything after the first colon will be used as the MySQL DSN. The display when connecting to the MySQL server is as follows:

<?php
$dbms = "mysql";                                  // 数据库的类型
$dbName ="php_cn";                                //使用的数据库名称
$user = "root";                                   //使用的数据库用户名
$pwd = "root";                                    //使用的数据库密码
$host = "localhost";                              //使用的主机名称
$dsn  = "$dbms:host=$host;dbname=$dbName";
try {
    $pdo = new PDO($dsn, $user, $pwd);//初始化一个PDO对象,就是创建了数据库连接对象$pdo
}catch (PDOException $e){
   echo "数据库连接失败:".$e->getMessage();
}
?>
Copy after login

Other drivers will also parse its DSN in different ways. If the driver cannot be loaded, or a connection failure occurs, a PDOException will be thrown so that you can You can decide how best to handle the failure. Omitting the try...catch control structure has no benefit; if exception handling is not defined at a higher level in the application, the script will terminate if the database connection cannot be established.

2. Store the parameters in the file

When creating a PDO object, you can put the DSN string in another local or remote location file, and reference this file in the constructor, as shown below:

<?php
try{
    $dbh = new PDO(&#39;uri:file:///usr/localhost/dbconnect&#39;,&#39;webuser&#39;,&#39;password&#39;);
}catch(PDOException $e){
    echo &#39;连接失败:&#39;.$e->getMessage();
}
?>
Copy after login

As long as the DSN driver in the file /usr/localhost/dbconnect is changed, you can switch between multiple database systems, but Make sure that the file is owned by the user responsible for executing the PHP script and that this user has the necessary permissions.

3. Reference the php.ini file

You can also maintain DSN information in the configuration file of the PHP server, as long as it is in the php.ini file Zhongba DSN information is passed to a configuration parameter named pdo.dsn.aliasname, where aliasname is the DSN alias that will be provided to the constructor later. Connect to the Oracle server as shown below. The alias specified for the DSN in php.ini is oraclepdo:

【PDO】
pdo.dsn.oraclepdo = “OCI:dbname=//localhost:1521/mydb;chaset=UTF-8”;
Copy after login

After restarting the Apaceh server, you can call the PDO construction method in the first PDO constructor in the PHP program. Use this alias in the parameters, as follows:

<?php
try{
    $dbh = new PDO(&#39;oraclepdo&#39;,&#39;scott&#39;,&#39;tiger&#39;);//使用php.ini文件中的oraclepdo 别名
}catch(PDOException $e){
    echo &#39;连接失败:&#39;.$e->getMessage();
}
?>
Copy after login

4. PDO connection-related options

When creating a PDO object, there are For some options related to database connection, you can pass the necessary options into an array to the fourth parameter driver_opts of the constructor to pass additional tuning parameters to PDO or the underlying driver. Some common usage options are as shown in the table:

选项名描述
PDO::ATTR_AUTOCOMMIT确定PDO是否关闭自定提交功能,设置FALSE值时关闭
PDO::ATTR_CASE强制PDO获取的表字段字符的大小转换,或远原样使用列信息
PDO::ATTR_ERRMODE设置错误处理的模式
PDO::ATTR_PERSISTENT确定连接是否为持久连接,默认值为FALSE
PDO::ATTR_ORACCLE_NULLS将返回的空字符串转换为SQL的NULL
PDO::ATTR_PREFETCH设置应用程序提前获取的数据大小,以K字节单位
PDO::ATTR_TIMEOUT设置超市之前等待的时间(秒数)
PDO::ATTR_SERVER_INFO包含与数据库特有的服务器信息
PDO::ATTR_SERVER_VERSION包含与数据库服务器版本号有关的信息
PDO::ATTR_CLIENT_VERSION包含与数据库客户端版本号有关的信息
PDO::ATTR_CONNECTION_STATUS包含数据库特有的与连接状态有关的信息

设置选项名为下表组成的关联数组,作为驱动程序特定的连接选项,传递给PDO构造方法的第四各参数中,在下面的实例中使用连接选项创建持久连接,持久连接的好处是能够避免在每个页面执行到打开和关闭数据库服务器连接,速度更快,如 MySQL数据库的一个进程创建了两个连接,PHP则会把原有连接与新的连接合并共享为一个连接,代码如下:

<?php
$opt = array(PDO::ATTR_PERSISTENT =>true);
try{
    $dbh = new PDO(&#39;mysql:host=localhost;dbname=test&#39;,&#39;dbuser&#39;,&#39;password&#39;,$opt); //使用$opt参数
}catch(PDOException $e){
    echo &#39;连接失败:&#39;.$e->getMessage();
}
?>
Copy after login

以上就是关于以多种方式调用构造方法创建PDO对象的所有内容,小伙伴们都理解了吗?可以在自己本地试一试!

The above is the detailed content of Call constructors in various ways to create PDO objects. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

When might a full table scan be faster than using an index in MySQL? When might a full table scan be faster than using an index in MySQL? Apr 09, 2025 am 12:05 AM

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Can I install mysql on Windows 7 Can I install mysql on Windows 7 Apr 08, 2025 pm 03:21 PM

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

Explain InnoDB Full-Text Search capabilities. Explain InnoDB Full-Text Search capabilities. Apr 02, 2025 pm 06:09 PM

InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

Difference between clustered index and non-clustered index (secondary index) in InnoDB. Difference between clustered index and non-clustered index (secondary index) in InnoDB. Apr 02, 2025 pm 06:25 PM

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values ​​and pointers to data rows, and is suitable for non-primary key column queries.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Can mysql and mariadb coexist Can mysql and mariadb coexist Apr 08, 2025 pm 02:27 PM

MySQL and MariaDB can coexist, but need to be configured with caution. The key is to allocate different port numbers and data directories to each database, and adjust parameters such as memory allocation and cache size. Connection pooling, application configuration, and version differences also need to be considered and need to be carefully tested and planned to avoid pitfalls. Running two databases simultaneously can cause performance problems in situations where resources are limited.

Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Explain different types of MySQL indexes (B-Tree, Hash, Full-text, Spatial). Apr 02, 2025 pm 07:05 PM

MySQL supports four index types: B-Tree, Hash, Full-text, and Spatial. 1.B-Tree index is suitable for equal value search, range query and sorting. 2. Hash index is suitable for equal value searches, but does not support range query and sorting. 3. Full-text index is used for full-text search and is suitable for processing large amounts of text data. 4. Spatial index is used for geospatial data query and is suitable for GIS applications.

See all articles