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!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.