> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/zh/web/sql-injection/union-attack-determining-number-of-columns.md).

# UNION 攻击列数检测

UNION 攻击列数检测笔记，适用于 PortSwigger Web Security Academy 实验室，包括利用流程、载荷测试、Burp Suite 验证和修复上下文。

### SQL 注入 UNION 攻击：确定查询返回的列数

* **背景：** `类别` 过滤器易受 SQL 注入攻击；应用程序响应包含 SQL 结果，因此 `UNION` 允许注入一条额外可见的行。
* **目标：** 找出原始查询返回的确切列数，以构建兼容的 `UNION SELECT`.
* **快速方法：**

1. **使用以下内容测试 `ORDER BY`** — 逐步增加索引，直到发生错误（该错误表示索引超过了列数）：

   ````
    ```sql
    ' ORDER BY 1-- -
    ' ORDER BY 2-- -
    ' ORDER BY 3-- -
    ```
   ````

* 当 `ORDER BY N` 会导致错误，则列数为 `< N`.

2. 通过注入包含 NULL 的 UNION 行进行确认——构建一个具有相同列数的 UNION SELECT；如果应用程序显示注入的行（空值），则列数正确。示例（3 列）：

   ```sql
   ' UNION SELECT NULL, NULL, NULL-- -
   ```

* 如果该行出现，则原始查询返回 3 列。否则，调整 `NULL` 的数量并重新测试。

**有用的变体：**

* 使用常量来定位显示的列（当只返回部分列时很有用）：

  ```sql
  ' UNION SELECT 'A', 'B', 'C'-- -
  ```

（这样可以直观识别响应中的哪些列对应注入的列。）

* 如果由于类型原因 UNION 失败，请根据 DBMS 将部分常量替换为 CAST(NULL AS VARCHAR2) / NULL，或使用 CAST/TO/CHAR 调整类型。

预期结果：将显示一行包含 NULL（或常量）的额外记录 → 已确定列数。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://hacking-notes.jord4n.pro/zh/web/sql-injection/union-attack-determining-number-of-columns.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
