PDO prepared statement PDOStatement object
This article mainly introduces a summary of the use of PDO preprocessing statements PDOStatement objects. This article introduces the methods of PDOStatement and examples of common methods. Friends in need can refer to
PDO support for preprocessing statements. You need to use the PDOStatement class object, but this class object is not instantiated through the NEW keyword, but is returned directly after preparing a preprocessed SQL statement in the database server through the prepare() method in the PDO object. If the PDOStatement class object returned by previously executing the query() method in the PDO object only represents a result set object. And if the PDOStatement class object generated by executing the prepare() method in the PDO object is a query object, it can define and execute parameterized SQL commands. All member methods in the PDOStatement class are as follows:
PDOStatement::bindColumn — 绑定一列到一个 PHP 变量 PDOStatement::bindParam — 绑定一个参数到指定的变量名 PDOStatement::bindValue — 把一个值绑定到一个参数 PDOStatement::closeCursor — 关闭游标,使语句能再次被执行。 PDOStatement::columnCount — 返回结果集中的列数 PDOStatement::debugDumpParams — 打印一条 SQL 预处理命令 PDOStatement::errorCode — 获取跟上一次语句句柄操作相关的 SQLSTATE PDOStatement::errorInfo — 获取跟上一次语句句柄操作相关的扩展错误信息 PDOStatement::execute — 执行一条预处理语句 PDOStatement::fetch — 从结果集中获取下一行 PDOStatement::fetchAll — 返回一个包含结果集中所有行的数组 PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列。 PDOStatement::fetchObject — 获取下一行并作为一个对象返回。 PDOStatement::getAttribute — 检索一个语句属性 PDOStatement::getColumnMeta — 返回结果集中一列的元数据 PDOStatement::nextRowset — 在一个多行集语句句柄中推进到下一个行集 PDOStatement::rowCount — 返回受上一个 SQL 语句影响的行数 PDOStatement::setAttribute — 设置一个语句属性 PDOStatement::setFetchMode — 为语句设置默认的获取模式。
1. Prepare statement
Repeatedly execute a SQL query, using different parameters through each iteration, this In this case, using prepared statements is the most efficient. To use prepared statements, you first need to prepare "a SQL statement" in the database server, but it does not need to be executed immediately. PDO supports the use of "placeholder" syntax to bind variables to this preprocessed SQL statement. For a prepared SQL statement, if some column values need to be changed each time it is executed, "placeholders" must be used instead of specific column values. There are two syntaxes for using placeholders in PDO: "named parameters" and "question mark parameters". Which syntax to use depends on personal preference.
Insert statement using named parameters as placeholders:
$dbh->prepare(“insert into contactinfo(name,address,phone) values(:name,:address,:phone)”);
You need to customize a string as a "named parameter". Each named parameter needs to start with a colon (:), and the parameter The name must be meaningful and preferably the same as the corresponding field name.
Insert statements using question mark (?) parameters as placeholders:
$dbh->prepare(“insert into contactinfo(name,address,phone) values(?,?,?)”);
The question mark parameters must correspond to the position order of the fields. No matter which parameter is used as a query composed of placeholders, or no placeholders are used in the statement, you need to use the prepare() method in the PDO object to prepare the query that will be used for iterative execution, and Returns a PDOStatement class object.
2. Binding parameters
When the SQL statement is prepared on the database server through the prepare() method in the PDO object, if a placeholder is used , you need to replace the input parameters every time it is executed. You can bind parameter variables to prepared placeholders through the bindParam() method in the PDOStatement object (the position or name must correspond). The prototype of the method bindParame() is as follows:
bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
The first parameter parameter is required. If the placeholder syntax uses name parameters in the prepared query, then the name parameter string is used as bindParam( ) method is provided as the first parameter. If the placeholder syntax uses a question mark argument, then the index offset of the column value placeholder in the prepared query is passed as the first argument to the method.
The second parameter variable is also optional and provides the value of the placeholder specified by the first parameter. Because the parameter is passed by reference, only variables can be provided as parameters, not values directly.
The third parameter data_type is optional and sets the data type for the currently bound parameter. Can be the following values.
PDO::PARAM_BOOL represents the boolean data type.
PDO::PARAM_NULL represents the NULL type in SQL.
PDO::PARAM_INT represents the INTEGER data type in SQL.
PDO::PARAM_STR represents CHAR, VARCHAR and other string data types in SQL.
PDO::PARAM_LOB represents the large object data type in SQL.
The fourth parameter length is optional and is used to specify the length of the data type.
The fifth parameter driver_options is optional and provides any database driver-specific options through this parameter.
Example of parameter binding using named parameters as placeholders:
<?php //...省略PDO连接数据库代码 $query = "insert into contactinfo (name,address,phone) values(:name,:address,:phone)"; $stmt = $dbh->prepare($query); //调用PDO对象中的prepare()方法 $stmt->blinparam(':name',$name); //将变量$name的引用绑定到准备好的查询名字参数":name"中 $stmt->blinparam(':address',$address); $stmt->blinparam(':phone',phone); //... ?>
Example of parameter binding using question marks (?) as placeholders:
<?php //...省略PDO连接数据库代码 $query = "insert into contactinfo (name,address,phone) values(?,?,?)"; $stmt = $dbh->prepare($query); //调用PDO对象中的prepare()方法 $stmt->blinparam(1,$name,PDO::PARAM_STR); //将变量$name的引用绑定到准备好的查询名字参数":name"中 $stmt->blinparam(2,$address,PDO::PARAM_STR); $stmt->blinparam(3,phone,PDO::PARAM_STR,20); //... ?>
3, Execute prepared statements
When the prepared statements are completed and the corresponding parameters are bound, you can repeatedly execute the prepared statements in the database cache by calling the execute() method in the PDOStatement class object. . In the following example, preprocessing is used to continuously execute the same INSERT statement in the contactinfo table provided earlier, and two records are added by changing different parameters. As shown below:
<?php try { $dbh = new PDO('mysql:dbname=testdb;host=localhost', $username, $passwd); }catch (PDOException $e){ echo '数据库连接失败:'.$e->getMessage(); exit; } $query = "insert into contactinfo (name,address,phone) values(?,?,?)"; $stmt = $dbh->prepare($query); $stmt->blinparam(1,$name); $stmt->blinparam(2,$address); $stmt->blinparam(3,phone); $name = "赵某某"; $address = "海淀区中关村"; $phone = "15801688348"; $stmt->execute(); //执行参数被绑定后的准备语句 ?>
If you are just passing input parameters and have many such parameters to be passed, then you will find the shortcut syntax shown below very helpful. This is the second way to replace input parameters for a preprocessed query during execution by providing an optional parameter in the execute() method, which is an array of named parameter placeholders in the prepared query. This syntax allows you to omit the call to $stmt->bindParam(). Modify the above example as follows:
<?php //...省略PDO连接数据库代码 $query = "insert into contactinfo (name,address,phone) values(?,?,?)"; $stmt = $dbh->prepare($query); //传递一个数组为预处理查询中的命名参数绑定值,并执行一次。 $stmt->execute(array("赵某某","海淀区","15801688348")); ?>
In addition, if an INSERT statement is executed and there is an automatically growing ID field in the data table, you can use the lastinsertId() method in the PDO object to obtain the last insert into the data table. The record ID in . If you need to check whether other DML statements are executed successfully, you can obtain the number of rows that affect the record through the rowCount() method in the PDOStatement class object.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Introduction to the import method of thinkPHP2.1 custom tag library
Use pthreads to achieve real PHP multi-threading method
The above is the detailed content of PDO prepared statement PDOStatement object. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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

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

1. Introduction to PDO PDO is an extension library of PHP, which provides an object-oriented way to operate the database. PDO supports a variety of databases, including Mysql, postgresql, oracle, SQLServer, etc. PDO enables developers to use a unified API to operate different databases, which allows developers to easily switch between different databases. 2. PDO connects to the database. To use PDO to connect to the database, you first need to create a PDO object. The constructor of the PDO object receives three parameters: database type, host name, database username and password. For example, the following code creates an object that connects to a mysql database: $dsn="mysq
