search
HomeBackend DevelopmentPHP TutorialPDO prepared statement PDOStatement object

PDO prepared statement PDOStatement object

Jul 03, 2018 pm 04:53 PM
pdoprepared statements

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(&#39;:name&#39;,$name);        //将变量$name的引用绑定到准备好的查询名字参数":name"中
$stmt->blinparam(&#39;:address&#39;,$address);
$stmt->blinparam(&#39;:phone&#39;,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(&#39;mysql:dbname=testdb;host=localhost&#39;, $username, $passwd);
}catch (PDOException $e){
    echo &#39;数据库连接失败:&#39;.$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!

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 is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft