How to get number of rows from prepared statement
Jul 17, 2025 am 12:45 AMGetting the number of rows affected by precompiled statements can be implemented in different ways: 1. When using PDO in PHP, call rowCount() or fetchAll and count(); 2. When using mysqli, call store_result() and access num_rows; 3. Node.js or Python count the length after obtaining the result array; 4. Note that some databases do not support direct acquisition, and need to be manually calculated or paging, LIMIT 1 and other methods to optimize performance. The core idea is to execute the statement first and then extract the row count information from the result set.
When using database development, it is a common requirement to get the number of rows affected by a prepared statement. For example, if you want to know how much data a query returns, or how many records a certain update operation has modified. Although there are slight differences between different languages and database systems, the overall idea is consistent.

1. Use PDO
(in PHP)
If you are using the PHP PDO extension to process precompiled statements, you can use rowCount()
method to get the number of affected rows:
$stmt = $pdo->prepare("SELECT * FROM users WHERE status = ?"); $stmt->execute([1]); // Get the number of rows $rowCount = $stmt->rowCount();
Note: rowCount()
may be inaccurate to SELECT statements in some database drivers (such as MySQL) or always return 0. At this time, it is recommended to get all the results first and then count().

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $count = count($rows);
2. Use mysqli
(in PHP)
In mysqli object-oriented method, you can directly access num_rows
attribute after executing the query:
$stmt = $mysqli->prepare("SELECT * FROM users WHERE status = ?"); $stmt->bind_param("i", $status); $stmt->execute(); $stmt->store_result(); echo $stmt->num_rows;
Note that you need to call store_result()
to get the number of rows correctly. Otherwise num_rows
may return 0.

3. Implementation in Node.js or Python
There are different methods for database libraries in different languages, but the core logic is similar:
- Node.js (mysql2/promise example) :
const [rows] = await connection.execute('SELECT * FROM users WHERE status = ?', [1]); console.log(rows.length);
- Python (using pymysql) :
cursor.execute("SELECT * FROM users WHERE status = %s", (1,)) rows = cursor.fetchall() print(len(rows))
As you can see, most of the time you have to take out the results first, and then count the number of rows through .length
or len()
.
4. Precautions and tips
- Not all databases support direct acquisition of row counts, and some require manual calculation.
- For large amounts of data, one-time fetchAll may take up a lot of memory, so paging can be considered.
- If you just judge whether there is a result, a more efficient way to get the total is to add
LIMIT 1
and see if there is a return. - Some databases (such as PostgreSQL) also support
RETURNING
clauses when executing UPDATE and DELETE, and can get the affected data at the same time.
Basically these are the methods. Different languages and database connection methods vary, but the core idea is to extract the quantity information from the result set after executing the statement. As long as you remember the process of "execute first, then fetch data", it will not be too difficult.
The above is the detailed content of How to get number of rows from prepared statement. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

In Linux systems, code statistics tools play a very important role. They can help developers understand the size and complexity of the code base, so as to better manage and optimize projects. So what are the common Linux code statistics tools? The following is a detailed introduction. In Linux development, there are some common code statistics tools to help developers understand the code size and structure. These tools can provide information such as the number of lines of code, number of files, etc. 1. Cloc: Cloc is a cross-platform command line tool, used to count the number of lines, comment lines and blank lines of source code, and supports multiple programming languages. SLOCCount is a flexible and customizable line-of-code counting tool that can analyze source code files in the project directory.

When we typeset word documents, we sometimes have to comply with many formatting requirements. For example, when we write papers or other more formal documents, there are many setting requirements, including requirements for fonts, font sizes, line spacing, etc. Sometimes There are even some regulations on the number of lines per page. So how do we set the number of word lines? Let’s try to practice it below, I hope it will help or inspire you! First, we need to create a new Word document and open it. In order to set the number of rows per page, we need to click on the "Page Layout" tab at the top of the page. Next, in the lower right corner we will see an icon that looks like a small square, which can be seen in the red box. The schematic is shown below. 2. After that, click the small square sign to pop up the [Page

In web development, connecting to the database is a crucial step. With the development of PHP, the PDO extension has become the preferred way to connect to databases because it is compatible with multiple databases and provides better error handling and security. This article will provide an in-depth understanding of the safety and execution efficiency of PDO prepared statements to help developers better use PDO to connect to the database. Overview of PDO prepared statements When using PDO to connect to a database, there are two commonly used SQL statements: ordinary statements and prepared statements. Ordinary statements directly change

The core of prevention of SQL injection lies in the use of preprocessing statements, which is the principle of separating SQL logic from data to prevent attackers from manipulating queries. The specific approach is: first define SQL queries with placeholders; then bind data values ??separately to ensure that the input is always regarded as data rather than executable code; finally, secure queries are implemented through PDO or MySQLi to avoid vulnerabilities and risks caused by manual escaping.

Execution of SELECT queries using PHP's preprocessing statements can effectively prevent SQL injection and improve security. 1. Preprocessing statements separate SQL structure from data, send templates first and then pass parameters to avoid malicious input tampering with SQL logic; 2. PDO and MySQLi extensions commonly used in PHP realize preprocessing, among which PDO supports multiple databases and unified syntax, suitable for newbies or projects that require portability; 3. MySQLi is specially designed for MySQL, with better performance but less flexibility; 4. When using it, you should select appropriate placeholders (such as? or named placeholders) and bind parameters through execute() to avoid manually splicing SQL; 5. Pay attention to processing errors and empty results to ensure the robustness of the code; 6. Close it in time after the query is completed.

Use prepared statements in PHP mainly to prevent SQL injection attacks, improve performance, make the code clearer and easier to debug. 1. It effectively prevents SQL injection through parameterized queries, ensuring that user input is always processed as data rather than SQL logic; 2. Preprocessing statements only need to be compiled once when executed multiple times, significantly improving execution efficiency, especially suitable for batch operations; 3. Parameter binding supports position and named placeholders, separates SQL and data, and enhances code readability and maintenance; 4. Errors can be exposed in advance in the prepare stage, and exceptions can be handled uniformly by setting error mode, which helps to quickly debug.

PreparedstatementsinMySQLipreventSQLinjectionandimproveefficiencybyseparatingSQLlogicfromdatainputs.Tousethemeffectively:1)connecttothedatabase,2)preparetheSQLstatementwithplaceholders,3)bindparameterscorrectlybytype(sforstring,iforinteger,etc.),4)ex

PHP preprocessing statements safely execute queries by separating SQL logic from data. 1. Use placeholders (such as ? or :name) instead of directly embedding user input; 2. bind values ??and then execute to ensure that the input is correctly escaped to prevent SQL injection; 3. Improve performance when executing similar queries multiple times; 4. Make the code clearer and easier to maintain; 5. Common errors include directly splicing user input into SQL, ignoring error handling, and replacing representative names or column names with placeholders.
