请有人在 sql 注射时解释这一步

some one explain this step while sql injecting please

在尝试理解 sqlinjection 时我没有理解这部分,首先这是我的代码

<?php
include "../chat/db.php";
if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $query = "select user_n,user_id from users where user_id<$id union select 1,2 ";
    $sql = mysqli_query($con, $query);
    if ($sql) {
        if (mysqli_num_rows($sql) > 0) {
            while ($result = mysqli_fetch_assoc($sql))
                echo "user name: " . $result["user_n"] . "of the id= " . $result["user_id"] . "</br>";

        } else {
            echo "there's no results";

        }

    }

} else {
    echo "error";
}
$tt = rand(0, 30);
?>
</br>
<a href=<?php echo "sql.php?id=" . $tt; ?>> <?php echo $tt; ?>  </a>    

如您在这张照片中看到的那样,结果很好 results

我不明白的是这个 union select 1,2 result

{用户名:1​​of the id=2} 出现是因为

union select 1,2

我的问题是为什么会这样显示,请问有人能解释一下 "select 1,2" 的这一步吗 谢谢你,如果有什么不清楚或者我解释不好我的观点,请原谅。

任何请求都可以通过SQL注入来操纵查询。

例如,我可以向您的页面发出请求:

http://example.com/chat/index.php?id=0+UNION+SELECT+TABLE_SCHEMA,TABLE_NAME+FROM+INFORMATION_SCHEMA.TABLES

基本上,任何人都可以注入任何 SQL 查询,只要该查询选择两个表达式即可。只需添加一个数字即可完成 id < $id 表达式,但 $id 的值可以继续传递给 PHP 代码的任何其他请求。

我不知道为什么查询包含 union select 1,2。我想这是 class 中的一个示例编码练习,教你 SQL 注入风险,union select 1,2 是讲师给你提示的一种方式 SQL注入涉及UNION。

您可以通过以下两种方式之一使此查询更安全:

  1. 将参数转换为数字,删除所有非数字部分:

    $id = (int) $_GET['id'];
    
  2. 使用查询参数:

    $query = "select user_n,user_id from users where user_id < ? union select 1,2 ";
    

有关查询参数的详细信息,请参阅 How can I prevent SQL injection in PHP?