


[PDO binding parameters] Use PHP's PDO extension to perform batch update operations, pdo binding_PHP tutorial
[PDO binding parameters] Use PHP's PDO extension to perform batch update operations. pdo binding
Recently there is a need to batch update certain fields in the database table. When meeting this requirement, I used PDO for parameter binding, but encountered a pitfall.
Plan selection
The author knows the following solutions for batch updates:
1. Update item by item
This is the simplest solution, but it is undoubtedly the least efficient one.
2.CASE WHEN
Sentences similar to the following
<span>UPDATE</span> tbl_test <span>SET</span> val <span>=</span> <span>CASE</span> id <span>WHEN</span> <span>1</span> <span>THEN</span> <span>2</span> <span>WHEN</span> <span>2</span> <span>THEN</span> <span>3</span> <span>END</span> <span>WHERE</span> id <span>IN</span>(<span>1</span>, <span>2</span>);
PDO binding parameters
To prevent SQL injection, PDO extended binding parameters are used. The above numbers are generally variables, so parameter binding is required. At first, I thought about binding the string composed of id as a variable during IN. The code for the first implementation is as follows:
<span> 1</span> <?<span>php </span><span> 2</span> <span>$data</span> = <span>array</span>(<span>array</span>('id' => 1, 'val' => 2), <span>array</span>('id' => 2, 'val' => 3<span>)); </span><span> 3</span> <span>$ids</span> = <span>implode</span>(',', <span>array_map</span>(<span>function</span>(<span>$v</span>) {<span>return</span> <span>$v</span>['id'];}, <span>$data</span>)); <span>//</span><span>获取ID数组</span> <span> 4</span> <span>$update_sql</span> = 'UPDATE tbl_test SET val = CASE id'<span>; </span><span> 5</span> <span>$params</span> = <span>array</span><span>(); </span><span> 6</span> <span>$params</span>[":ids"] = <span>$ids</span><span>; </span><span> 7</span> <span>foreach</span>(<span>$data</span> <span>as</span> <span>$key</span> => <span>$item</span><span>) { </span><span> 8</span> <span>$update_sql</span> .= "WHEN :id_" . <span>$key</span> . "THEN :val_" . <span>$key</span> . " "<span>; </span><span> 9</span> <span>$params</span>[":id_" . <span>$key</span>] = <span>$item</span>['id'<span>]; </span><span>10</span> <span>$params</span>[":val_" . <span>$key</span>] = <span>$item</span>['val'<span>]; </span><span>11</span> <span> } </span><span>12</span> <span>$update_sql</span> .= "END WHERE id IN (:_ids)"<span>; </span><span>13</span> <span>TEST::</span>execute(<span>$update_sql</span>, <span>$params</span>);//此处会调用bindParam绑定参数
Later I found out that this doesn’t work, and what’s weird is that only the first record can be updated in this way. After consulting the information, I found that this binding method is not feasible. The parameters of the IN statement should be bound one by one. Take a look at the description of the bindParam function in the documentation:
As you can see, the description says that a PHP variable will be bound to the placeholder, so if a string with :ids of 1, 2 is bound, then MySQL will use 1, 2 when parsing the statement. Parsed as a single variable, not as a string. This is also the principle of PDO to prevent SQL injection. Through the binding of placeholders, only the bound value is regarded as a value, not other things such as statements. In this way, MySQL will only treat the passed value as a variable. value.
Modified writing:
<span> 1</span> <?<span>php </span><span> 2</span> <span>$data</span> = <span>array</span>(<span>array</span>('id' => 1, 'val' => 2), <span>array</span>('id' => 2, 'val' => 3<span>)); </span><span> 3</span> <span>$update_sql</span> = 'UPDATE tbl_test SET val = CASE id'<span>; </span><span> 4</span> <span>$params</span> = <span>array</span><span>(); </span><span> 5</span> <span>$params</span>[":ids"] = <span>$ids</span><span>; </span><span> 6</span> <span>$in_arr</span> = <span>array</span><span>(); </span><span> 7</span> <span> 8</span> <span>foreach</span>(<span>$data</span> <span>as</span> <span>$key</span> => <span>$item</span><span>) { </span><span> 9</span> <span>$update_sql</span> .= "WHEN :id_" . <span>$key</span> . "THEN :val_" . <span>$key</span> . " "<span>; </span><span>10</span> <span>$params</span>[":id_" . <span>$key</span>] = <span>$item</span>['id'<span>]; </span><span>11</span> <span>$params</span>[":val_" . <span>$key</span>] = <span>$item</span>['val'<span>]; </span><span>12</span> <span>$params</span>[":ids_" . <span>$key</span>] = <span>$item</span>['id'<span>]; </span><span>13</span> <span>array_push</span>(<span>$in_arr</span>, ":id_" . <span>$key</span><span>); </span><span>14</span> <span> } </span><span>15</span> <span>$update_sql</span> .= "END WHERE id IN (" . <span>implode</span>(',' <span>$in_arr</span>) . ")"<span>; </span><span>16</span> TEST::execute(<span>$update_sql</span>, <span>$params</span>);<span>//</span><span>此处会调用bindParam绑定参数</span>
Summary
This is a small problem I encountered recently. In fact, it is more about illustrating that when binding parameters in the IN statement of MySQL, you should bind them one by one.
Reference link:
mysql statement: batch update different values of multiple records
Can I bind an array to an IN() condition?
Original article with limited writing style and limited knowledge. If there is anything wrong in the article, please let me know.
If this article is helpful to you, please click Recommend. Writing articles is not easy.

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

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

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

How to use PDO to connect to the Redis database. Redis is an open source, high-performance, in-memory storage key-value database that is commonly used in cache, queue and other scenarios. In PHP development, using Redis can effectively improve the performance and stability of applications. Through the PDO (PHPDataObjects) extension, we can connect and operate the Redis database more conveniently. This article will introduce how to use PDO to connect to a Redis database, with code examples. Install the Redis extension at the beginning

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
