search
HomeBackend DevelopmentPHP TutorialPDO prepared statement PDOStatement object usage summary, pdopdostatement_PHP tutorial

Summary of the use of PDO prepared statements PDOStatement objects, pdopdostatement

PDO’s support for prepared statements requires the use of PDOStatement class objects, but this class object is not instantiated through the NEW keyword, but is prepared in the database server through the prepare() method in the PDO object. Returned directly after the preprocessed SQL statement. 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:

Copy code The code is as follows:

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 — Closes 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 row and returns it as an object.
PDOStatement::getAttribute — Retrieve a statement attribute
PDOStatement::getColumnMeta — Returns metadata for 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.

1. Prepare statements

Repeatedly execute a SQL query, using different parameters for each iteration. In this case, prepared statements are 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:

Copy code The code is as follows:

$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 (:). The naming of the parameter must be meaningful, and it is best to have the same name as the corresponding field name.
INSERT statement using question mark (?) parameter as placeholder:
Copy code The code is as follows:

$dbh->prepare(“insert into contactinfo(name,address,phone) values(?,?,?)”);

The question mark parameter 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 placeholders are used, the input parameters need to be replaced each time it is executed. You can bind parameter variables to prepared placeholders (the position or name must correspond) through the bindParam() method in the PDOStatement object. The prototype of the method bindParame() is as follows:

Copy code The code 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 named parameters in the prepared query, then the named parameter string is provided as the first parameter of the bindParam() method. 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:

Copy code The code is as follows:

//...Omit the PDO connection database code
$query = "insert into contactinfo (name,address,phone) values(:name,:address,:phone)";
$stmt = $dbh->prepare($query); //Call the prepare() method in the PDO object

$stmt->blinparam(':name',$name); //Bind the reference of variable $name to the prepared query name parameter ":name"
$stmt->blinparam(':address',$address);
$stmt->blinparam(':phone',phone);
//...
?>

Example of parameter binding using question mark (?) as placeholder:

Copy code The code is as follows:

//...Omit the PDO connection database code
$query = "insert into contactinfo (name,address,phone) values(?,?,?)";
$stmt = $dbh->prepare($query); //Call the prepare() method in the PDO object

$stmt->blinparam(1,$name,PDO::PARAM_STR); //Bind the reference of variable $name to the prepared query name parameter ":name"
$stmt->blinparam(2,$address,PDO::PARAM_STR);
$stmt->blinparam(3,phone,PDO::PARAM_STR,20);
//...
?>

3. Execute prepared statements

When the prepared statement is completed and the corresponding parameters are bound, you can repeatedly execute the statement prepared 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:

Copy code The code is as follows:

try {
$dbh = new PDO('mysql:dbname=testdb;host=localhost', $username, $passwd);
}catch (PDOException $e){
echo 'Database connection failed:'.$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 = "Zhao XX";
$address = "Zhongguancun, Haidian District";
$phone = "15801688348";

$stmt->execute(); //The prepared statement after the execution parameters are bound
?>

If you are just passing input parameters and have many such parameters to pass, 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 eliminate the call to $stmt->bindParam(). Modify the above example as follows:
Copy code The code is as follows:

//...Omit the PDO connection database code
$query = "insert into contactinfo (name,address,phone) values(?,?,?)";
$stmt = $dbh->prepare($query);

//Pass an array to bind values ​​to the named parameters in the preprocessed query and execute it once.
$stmt->execute(array("Zhao XX","Haidian District","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 ID of the record last inserted into the data table. 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/915442.htmlTechArticle Summary of the use of PDO statement PDOStatement objects, pdopdostatement PDO's support for prepared statements requires the use of PDOStatement class objects, but Objects of this class are not instantiated through the NEW keyword...
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
PHP Fatal error: Call to undefined method PDO::prepare() in的解决方法PHP Fatal error: Call to undefined method PDO::prepare() in的解决方法Jun 22, 2023 pm 06:40 PM

PHP作为一种流行的Web开发语言,已经被使用了很长时间。PHP中集成的PDO(PHP数据对象)类是我们在开发Web应用程序过程中与数据库进行交互的一种常用方法。但是,一些PHP开发者经常遇到的问题是,当使用PDO类与数据库进行交互时,他们会收到这样的错误:PHPFatalerror:CalltoundefinedmethodPDO::prep

php如何使用PHP的PDO_PGSQL扩展?php如何使用PHP的PDO_PGSQL扩展?Jun 02, 2023 pm 06:10 PM

PHP作为一种流行的编程语言,在Web开发领域中有着广泛的应用。其中,PHP的PDO_PGSQL扩展是一种常用的PHP扩展,它提供了与PostgreSQL数据库的交互接口,可以实现PHP与PostgreSQL之间的数据传输和交互。本文将详细介绍如何使用PHP的PDO_PGSQL扩展。一、什么是PDO_PGSQL扩展?PDO_PGSQL是PHP的一个扩展库,它

PHP和PDO: 如何执行批量插入和更新PHP和PDO: 如何执行批量插入和更新Jul 28, 2023 pm 07:41 PM

PHP和PDO:如何执行批量插入和更新导言:在使用PHP编写数据库相关的应用程序时,经常会遇到需要批量插入和更新数据的情况。传统的做法是使用循环来执行多次数据库操作,但这样的方法效率较低。PHP的PDO(PHPDataObject)提供了一种更高效的方法来执行批量插入和更新操作,本文将介绍如何使用PDO来实现批量插入和更新。一、PDO简介:PDO是PH

PHP和PDO: 如何处理数据库中的JSON数据PHP和PDO: 如何处理数据库中的JSON数据Jul 29, 2023 pm 05:17 PM

PHP和PDO:如何处理数据库中的JSON数据在现代web开发中,处理和存储大量数据是一个非常重要的任务。随着移动应用和云计算的普及,越来越多的数据以JSON(JavaScriptObjectNotation)格式存储在数据库中。PHP作为一种常用的服务器端语言,它的PDO(PHPDataObject)扩展提供了一种方便的方式来处理和操作数据库。本

PHP和PDO: 如何进行分页查询和显示数据PHP和PDO: 如何进行分页查询和显示数据Jul 29, 2023 pm 04:10 PM

PHP和PDO:如何进行分页查询和显示数据在开发Web应用程序时,分页查询和显示数据是一个非常常见的需求。通过分页,我们可以一次显示一定数量的数据,提高页面加载速度和用户体验。在PHP中,使用PHP数据对象(PDO)库可以轻松实现分页查询和显示数据的功能。本文将介绍如何在PHP中使用PDO进行分页查询和显示数据,并提供相应的代码示例。一、创建数据库和数据表

PHP和PDO: 如何执行数据库备份和还原操作PHP和PDO: 如何执行数据库备份和还原操作Jul 29, 2023 pm 06:54 PM

PHP和PDO:如何执行数据库备份和还原操作在开发Web应用程序时,数据库的备份和还原是非常重要的任务。PHP作为一门流行的服务器端脚本语言,提供了丰富的库和扩展,其中PDO(PHP数据对象)是一款强大的数据库访问抽象层。本文将介绍如何使用PHP和PDO来执行数据库备份和还原操作。第一步:连接数据库在实际操作之前,我们需要建立与数据库的连接。使用PDO对

如何使用PDO连接到Redis数据库如何使用PDO连接到Redis数据库Jul 28, 2023 pm 04:29 PM

如何使用PDO连接到Redis数据库Redis是一个开源的高性能、内存存储的键值数据库,常用于缓存、队列等场景。在PHP开发中,使用Redis可以有效提升应用的性能和稳定性。而通过PDO(PHPDataObjects)扩展,我们可以更方便地连接和操作Redis数据库。本文将介绍如何使用PDO连接到Redis数据库,并附带代码示例。安装Redis扩展在开始

如何使用PDO绑定和获取绑定参数值如何使用PDO绑定和获取绑定参数值Jul 28, 2023 pm 07:09 PM

如何使用PDO绑定和获取绑定参数值在开发Web应用程序时,处理数据库查询是很常见的任务之一。为了保证应用程序的安全性和可靠性,我们应该使用参数绑定来处理SQL查询,而不是直接将变量值插入SQL语句中。PDO(PHP数据对象)提供了一种方便且安全的方式来绑定参数和获取绑定参数的值。下面,我们将介绍如何使用PDO进行参数绑定和获取绑定参数的

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools