Table of Contents
php pdo operates the database, phppdo database
Home Backend Development PHP Tutorial php pdo operation database, phppdo database_PHP tutorial

php pdo operation database, phppdo database_PHP tutorial

Jul 12, 2016 am 08:53 AM
pdo

php pdo operates the database, phppdo database

POD extension is added in PHP5. This extension provides PHP built-in class PDO to access the database. Different databases use the same method name , solve the problem of inconsistent database connections.

Features of PDO:

Performance. PDO learned from the beginning about the successes and failures of scaling existing databases. Because PDO's code is brand new, we have the opportunity to redesign performance from the ground up to take advantage of PHP 5's latest features.
Ability. PDO is designed to provide common database functionality as a foundation while providing easy access to the unique features of an RDBMS.
Simple. PDO is designed to make working with databases easy for you. The API doesn't force its way into your code and makes it clear what each function call does.
Extensible at runtime. The PDO extension is modular, enabling you to load drivers for your database backend at runtime without having to recompile or reinstall the entire PHP program. For example, the PDO_OCI extension implements the oracle database API instead of the PDO extension. There are also drivers for MySQL, PostgreSQL, ODBC, and Firebird, with more in development.

PDO installation

You can check whether the PDO extension is installed through PHP’s phpinfo() function.

 1. Install PDO on Unix/Linux system

On Unix or Linux you need to add the following extension:

 extension=pdo.so

 2. Install pdo
in Windows

PDO and all major drivers are shipped with PHP as shared extensions, to activate them simply edit the php.ini file and add the following extension:

  extension=php_pdo.dll

In addition, there are various database extensions corresponding to the following:

<span class="pln"><span class="pun">    ;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_firebird<span class="pun">.<span class="pln">dll
    <span class="pln"><span class="pun"><span class="pln"><span class="pun"><span class="pln"><span class="pun"><span class="pln"><span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_informix<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_mssql<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_mysql<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_oci<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_oci8<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_odbc<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_pgsql<span class="pun">.<span class="pln">dll
    <span class="pun">;<span class="pln">extension<span class="pun">=<span class="pln">php_pdo_sqlite<span class="pun">.<span class="pln">dll</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>
Copy after login

Open php.ini and remove the semicolons in front of all the lines above.
After setting these configurations, we need to restart PHP or Web server.

Next we use mysql as an example to use pdo:

<?<span>php
$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='test';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName"<span>;


try<span> {
    $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    echo "连接成功<br/>"<span>;
    /*你还可以进行一次搜索操作
    foreach ($dbh->query('SELECT * from FOO') as $row) {
        print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
    }
    */
    $dbh = null<span>;
} catch (PDOException $e<span>) {
    die ("Error!: " . $e->getMessage() . "<br/>"<span>);
}
//默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(PDO::ATTR_PERSISTENT => true) 变成这样:
$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true<span>));

?></span></span></span></span></span></span></span></span>
Copy after login

 Let’s take a look at the detailed introduction of pdo:

1. Predefined constants:

2.PDO class:

    • PDO::beginTransaction — Start a transaction
    • PDO::commit — Commit a transaction
    • PDO::__construct — Create a PDO instance that represents a database connection
    • PDO::errorCode — Get the SQLSTATE
    • related to the last operation of the database handle
    • PDO::errorInfo — Returns the error message of the last database operation
    • PDO::exec — Execute a SQL statement and return the number of affected rows
    • PDO::getAttribute — Retrieve attributes of a database connection
    • PDO::getAvailableDrivers — Returns an array of available drivers
    • PDO::inTransaction — Check if it is within a transaction
    • PDO::lastInsertId — Returns the ID or sequence value of the last inserted row
    • PDO::prepare — Prepares the SQL statement to be executed and returns a PDOStatement object
    • PDO::query — Execute SQL statements and return PDOStatement objects, which can be understood as result sets
    • PDO::quote — Add quotes to strings in SQL statements.
    • PDO::rollBack — Roll back a transaction
    • PDO::setAttribute — Set attributes
    • PDOStatement class:
      • PDOStatement::bindColumn — Bind a column to a PHP variable
      • PDOStatement::bindParam — Bind a parameter to the specified variable name
      • PDOStatement::bindValue — Bind a value to a parameter
      • PDOStatement::closeCursor — Close the cursor so that the statement can be executed again.
      • PDOStatement::columnCount — Returns the number of columns in the result set
      • PDOStatement::debugDumpParams — Print a SQL preprocessing command
      • PDOStatement::errorCode — Get the SQLSTATE
      • related to the last statement handle operation
      • PDOStatement::errorInfo — Get extended error information related to the last statement handle operation
      • PDOStatement::execute — execute a prepared statement
      • PDOStatement::fetch — Get the next row from the result set
      • PDOStatement::fetchAll — Returns an array containing all rows in the result set
      • PDOStatement::fetchColumn — Returns a single column from the next row in the result set.
      • PDOStatement::fetchObject — Gets the next line and returns it as an object.
      • PDOStatement::getAttribute — Retrieve a statement attribute
      • PDOStatement::getColumnMeta — Returns the metadata of a column in the result set
      • PDOStatement::nextRowset — Advance to the next rowset in a multi-rowset statement handle
      • PDOStatement::rowCount — Returns the number of rows affected by the previous SQL statement
      • PDOStatement::setAttribute — Set a statement attribute
      • PDOStatement::setFetchMode — Set the default fetch mode for statements.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1125063.htmlTechArticlephp pdo operates the database. The phppdo database POD extension was added in PHP5. This extension provides PHP built-in class PDO to Database is accessed. Different databases use the same method name to solve the problem...
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)

Solution to PHP Fatal error: Call to undefined method PDO::prepare() in Solution to PHP Fatal error: Call to undefined method PDO::prepare() in Jun 22, 2023 pm 06:40 PM

PHP is a popular web development language that has been used for a long time. The PDO (PHP Data Object) class integrated in PHP is a common way for us to interact with the database during the development of web applications. However, a problem that some PHP developers often encounter is that when using the PDO class to interact with the database, they receive an error like this: PHPFatalerror:CalltoundefinedmethodPDO::prep

How to use PHP's PDO_PGSQL extension? How to use PHP's PDO_PGSQL extension? Jun 02, 2023 pm 06:10 PM

As a popular programming language, PHP is widely used in the field of web development. Among them, PHP's PDO_PGSQL extension is a commonly used PHP extension. It provides an interactive interface with the PostgreSQL database and can realize data transmission and interaction between PHP and PostgreSQL. This article will introduce in detail how to use PHP's PDO_PGSQL extension. 1. What is the PDO_PGSQL extension? PDO_PGSQL is an extension library of PHP, which

PHP and PDO: How to perform bulk inserts and updates PHP and PDO: How to perform bulk inserts and updates Jul 28, 2023 pm 07:41 PM

PHP and PDO: How to perform batch inserts and updates Introduction: When using PHP to write database-related applications, you often encounter situations where you need to batch insert and update data. The traditional approach is to use loops to perform multiple database operations, but this method is inefficient. PHP's PDO (PHPDataObject) provides a more efficient way to perform batch insert and update operations. This article will introduce how to use PDO to implement batch insert and update operations. 1. Introduction to PDO: PDO is PH

PHP PDO vs. mysqli: compare and contrast PHP PDO vs. mysqli: compare and contrast Feb 19, 2024 pm 12:24 PM

PDOPDO is an object-oriented database access abstraction layer that provides a unified interface for PHP, allowing you to use the same code to interact with different databases (such as Mysql, postgresql, oracle). PDO hides the complexity of underlying database connections and simplifies database operations. Advantages and Disadvantages Advantages: Unified interface, supports multiple databases, simplifies database operations, reduces development difficulty, provides prepared statements, improves security, supports transaction processing Disadvantages: performance may be slightly lower than native extensions, relies on external libraries, may increase overhead, demo code uses PDO Connect to mysql database: $db=newPDO("mysql:host=localhost;dbnam

PHP and PDO: How to perform paging queries and display data PHP and PDO: How to perform paging queries and display data Jul 29, 2023 pm 04:10 PM

PHP and PDO: How to query and display data in pages When developing web applications, querying and displaying data in pages is a very common requirement. Through paging, we can display a certain amount of data at a time, improving page loading speed and user experience. In PHP, the functions of paging query and display of data can be easily realized using the PHP Data Object (PDO) library. This article will introduce how to use PDO in PHP to query and display data by page, and provide corresponding code examples. 1. Create database and data tables

PHP and PDO: How to handle JSON data in a database PHP and PDO: How to handle JSON data in a database Jul 29, 2023 pm 05:17 PM

PHP and PDO: How to handle JSON data in databases In modern web development, processing and storing large amounts of data is a very important task. With the popularity of mobile applications and cloud computing, more and more data are stored in databases in JSON (JavaScript Object Notation) format. As a commonly used server-side language, PHP's PDO (PHPDataObject) extension provides a convenient way to process and operate databases. Book

PHP and PDO: How to perform a full-text search in a database PHP and PDO: How to perform a full-text search in a database Jul 30, 2023 pm 04:33 PM

PHP and PDO: How to perform a full-text search in a database In modern web applications, the database is a very important component. Full-text search is a very useful feature when we need to search for specific information from large amounts of data. PHP and PDO (PHPDataObjects) provide a simple yet powerful way to perform full-text searches in databases. This article will introduce how to use PHP and PDO to implement full-text search, and provide some sample code to demonstrate the process. first

PHP and PDO: How to perform database backup and restore operations PHP and PDO: How to perform database backup and restore operations Jul 29, 2023 pm 06:54 PM

PHP and PDO: How to perform database backup and restore operations When developing web applications, database backup and restore are very important tasks. As a popular server-side scripting language, PHP provides a wealth of libraries and extensions, among which PDO (PHP Data Objects) is a powerful database access abstraction layer. This article will introduce how to use PHP and PDO to perform database backup and restore operations. Step 1: Connect to the database Before actual operation, we need to establish a connection to the database. Use PDO pair

See all articles
PDO::PARAM_BOOL (integer) represents the Boolean data type.
PDO::PARAM_NULL (integer) represents the NULL data type in SQL.
PDO::PARAM_INT (integer) represents an integer type in SQL.
PDO::PARAM_STR (integer) represents CHAR, VARCHAR or other string types in SQL.
PDO::PARAM_LOB (integer) represents the large object data type in SQL.
PDO::PARAM_STMT (integer) represents a recordset type. It is not currently supported by any driver.
PDO::PARAM_INPUT_OUTPUT (integer) The specified parameter is an INOUT parameter of a stored procedure. This value must be bitwise ORed with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY (integer) Specify the acquisition method and return each row in the result set as an object. The variable name of this object corresponds to the column name. PDO::FETCH_LAZY creates the object variable name for access. Not valid in PDOStatement::fetchAll().
PDO::FETCH_ASSOC (integer) Specify the acquisition method and return each row in the corresponding result set as an array indexed by the column name. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only one value per column name.
PDO::FETCH_NAMED (integer) Specify the acquisition method and return each row in the corresponding result set as an array indexed by the column name. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns an array containing values ​​for each column name.
PDO::FETCH_NUM (integer) Specify the acquisition method and return each row in the corresponding result set as an array indexed by the column number, starting from column 0.
PDO::FETCH_BOTH (integer) Specify the acquisition method and return each row in the corresponding result set as an array indexed by column number and column name, starting from column 0.
PDO::FETCH_OBJ (integer) Specify the acquisition method and return each row in the result set as an object whose attribute name corresponds to the column name.
PDO::FETCH_BOUND (integer) Specify the acquisition method, return TRUE and assign the column value in the result set to the PHP variable bound through the PDOStatement::bindParam() or PDOStatement::bindColumn() method.
PDO::FETCH_COLUMN (integer) Specify the acquisition method and return the required column from the next row in the result set.
PDO::FETCH_CLASS (integer) Specify the acquisition method, return a new instance of the requested class, and map the column to the corresponding attribute name in the class.

Note: If the attribute does not exist in the requested class, the __set() magic method is called

PDO::FETCH_INTO (integer) Specify the acquisition method, update an existing instance of the requested class, and map the column to the corresponding attribute name in the class.
PDO::FETCH_FUNC (integer) Allows data to be processed in completely custom ways on the fly. (Only valid in PDOStatement::fetchAll()).
PDO::FETCH_GROUP (integer) Return grouped by value. Typically used with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (integer) Only take unique values.
PDO::FETCH_KEY_PAIR (integer) Get a result set with two columns into an array, where the first column is the key name and the second column is the value. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer) Determine the class name based on the value of the first column.
PDO::FETCH_SERIALIZE (integer) Similar to PDO::FETCH_INTO, but represents the object as a serialized string. Available since PHP 5.1.0. Starting with PHP 5.3.0, if this flag is set, the class's constructor is never called.
PDO::FETCH_PROPS_LATE (integer) Call the constructor before setting properties. Available since PHP 5.2.0.
PDO::ATTR_AUTOCOMMIT (integer) If this value is FALSE , PDO will attempt to disable autocommit in order for the database connection to start a transaction.
PDO::ATTR_PREFETCH (integer) Set the prefetch size to balance speed and memory usage for your application. Not all database/driver combinations support setting the prefetch size. Larger prefetch sizes result in improved performance but also consume more memory.
PDO::ATTR_TIMEOUT (integer) Set the timeout seconds for connecting to the database.
PDO::ATTR_ERRMODE (integer) See the Errors and Error Handling section for more information about this property.
PDO::ATTR_SERVER_VERSION (integer) This is a read-only property; returns the version information of the database service connected to PDO.
PDO::ATTR_CLIENT_VERSION (integer) This is a read-only property; returns the version information of the client library used by the PDO driver.
PDO::ATTR_SERVER_INFO (integer) This is a read-only property. Returns some meta-information about the database service to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer) Use constants like PDO::CASE_* to force column names to the specified case.
PDO::ATTR_CURSOR_NAME (integer) Gets or sets the name of the cursor to use. Very useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer) Select the cursor type. PDO currently supports PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Typically PDO::CURSOR_FWDONLY unless a scrollable cursor is really needed.
PDO::ATTR_DRIVER_NAME (string) Returns the driver name.

Example using PDO::ATTR_DRIVER_NAME:

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
  echo "Running on mysql; doing something mysql specific here\n";
}
?>
Copy after login
PDO::ATTR_ORACLE_NULLS (integer) 在获取数据时将空字符串转换成 SQL 中的 NULL 。
PDO::ATTR_PERSISTENT (integer) 请求一个持久连接,而非创建一个新连接。关于此属性的更多信息请参见 连接与连接管理 。
PDO::ATTR_STATEMENT_CLASS (integer)  
PDO::ATTR_FETCH_CATALOG_NAMES (integer) 将包含的目录名添加到结果集中的每个列名前面。目录名和列名由一个小数点分开(.)。此属性在驱动层面支持,所以有些驱动可能不支持此属性。
PDO::ATTR_FETCH_TABLE_NAMES (integer) 将包含的表名添加到结果集中的每个列名前面。表名和列名由一个小数点分开(.)。此属性在驱动层面支持,所以有些驱动可能不支持此属性。
PDO::ATTR_STRINGIFY_FETCHES (integer)  
PDO::ATTR_MAX_COLUMN_LEN (integer)  
PDO::ATTR_DEFAULT_FETCH_MODE (integer) 自 PHP 5.2.0 起可用。
PDO::ATTR_EMULATE_PREPARES (integer) 自 PHP 5.1.3 起可用。
PDO::ERRMODE_SILENT (integer) 如果发生错误,则不显示错误或异常。希望开发人员显式地检查错误。此为默认模式。关于此属性的更多信息请参见 错误与错误处理 。
PDO::ERRMODE_WARNING (integer) 如果发生错误,则显示一个 PHP E_WARNING 消息。关于此属性的更多信息请参见 错误与错误处理。
PDO::ERRMODE_EXCEPTION (integer) 如果发生错误,则抛出一个 PDOException 异常。关于此属性的更多信息请参见 错误与错误处理。
PDO::CASE_NATURAL (integer) 保留数据库驱动返回的列名。
PDO::CASE_LOWER (integer) 强制列名小写。
PDO::CASE_UPPER (integer) 强制列名大写。
PDO::NULL_NATURAL (integer)  
PDO::NULL_EMPTY_STRING (integer)  
PDO::NULL_TO_STRING (integer)  
PDO::FETCH_ORI_NEXT (integer) 在结果集中获取下一行。仅对可滚动游标有效。
PDO::FETCH_ORI_PRIOR (integer) 在结果集中获取上一行。仅对可滚动游标有效。
PDO::FETCH_ORI_FIRST (integer) 在结果集中获取第一行。仅对可滚动游标有效。
PDO::FETCH_ORI_LAST (integer) 在结果集中获取最后一行。仅对可滚动游标有效。
PDO::FETCH_ORI_ABS (integer) 根据行号从结果集中获取需要的行。仅对可滚动游标有效。
PDO::FETCH_ORI_REL (integer) 根据当前游标位置的相对位置从结果集中获取需要的行。仅对可滚动游标有效。
PDO::CURSOR_FWDONLY (integer) 创建一个只进游标的 PDOStatement 对象。此为默认的游标选项,因为此游标最快且是 PHP 中最常用的数据访问模式。
PDO::CURSOR_SCROLL (integer) 创建一个可滚动游标的 PDOStatement 对象。通过 PDO::FETCH_ORI_* 常量来控制结果集中获取的行。
PDO::ERR_NONE (string) 对应 SQLSTATE '00000',表示 SQL 语句没有错误或警告地成功发出。当用 PDO::errorCode() 或 PDOStatement::errorCode() 来确定是否有错误发生时,此常量非常方便。在检查上述方法返回的错误状态代码时,会经常用到。
PDO::PARAM_EVT_ALLOC (integer) 分配事件
PDO::PARAM_EVT_FREE (integer) 解除分配事件
PDO::PARAM_EVT_EXEC_PRE (integer) 执行一条预处理语句之前触发事件。
PDO::PARAM_EVT_EXEC_POST (integer) 执行一条预处理语句之后触发事件。
PDO::PARAM_EVT_FETCH_PRE (integer) 从一个结果集中取出一条结果之前触发事件。
PDO::PARAM_EVT_FETCH_POST (integer) 从一个结果集中取出一条结果之后触发事件。
PDO::PARAM_EVT_NORMALIZE (integer) 在绑定参数注册允许驱动程序正常化变量名时触发事件。