search
HomeDatabaseMysql TutorialCall constructors in various ways to create PDO objects

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();
}
?>

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();
}
?>

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();
}
?>

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”;

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();
}
?>

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();
}
?>

以上就是关于以多种方式调用构造方法创建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
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
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version