1

在我意识到准备好的语句的使用以及它对 SQL 注入的作用之前,我编写了这段代码。现在我也知道使用准备好的语句获取数组是多么的混乱。所以我想知道这段代码是否可以安全使用,因为它不使用任何用户提交的信息来获取行。

它的作用是通过使用会话 id 来识别 db 表中的行,会话由 login_check 函数等确保......:

$username = $_SESSION['username'];
$select = mysqli_query($link, " SELECT product_id, product_title, product_value                             
                                FROM product
                                WHERE user_id='$username'");

while ($row = mysqli_fetch_assoc($select))
{
    $product[] = array(
            'product_id' => $row['product_id'], 
            'product_title' => $row['product_title'], 
            'product_value' => $row['product_value']);
}

关于这个问题的一些信息真的很感激,因为事情进展顺利,直到我知道准备好的陈述..

编辑
所以,我有点朝另一个方向走,并完全跳过了这个查询的数组部分。相反,我使用准备好的声明并做了这样的事情..:

$select_stmt = $db->prepare("SELECT etc...)
$select_stmt->bind_param("CODE")
$select_stmt->execute();
等等..

但问题是我的 bind_result 变得相当大(?)有 14 个变量。也许这是一个愚蠢的问题,但与使用单个数组的旧方法相比,这会减慢我的网站速度(如果 14 甚至被认为是“大”)?这是一个常见的查询,希望许多用户会同时经常使用它。准备好的陈述对我来说是新的,所以..

感谢到目前为止的帮助。

4

2 回答 2

1

您应该查看准备好的陈述。这是 mysqli 的众多好处之一。它允许您插入变量而不必担心 SQL 注入。mysqli_real_escape_string大多数时候都可以工作,但准备好的语句是唯一真正安全的避免攻击的方法。

手册中的示例:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($district);

    /* fetch value */
    $stmt->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $stmt->close();
}
于 2012-08-24T13:37:56.923 回答
1

如果用户名是例如Jean D'arc到达 mysql 服务器的字符串将是

SELECT
  product_id, product_title, product_value
FROM
  product
WHERE
  user_id='Jean D'arc'

这将导致解析错误。
正确编码/转义 sql 语句中的参数不仅对于防止来自用户的恶意输入是必要的,而且对于您不能(绝对肯定)确保它不包含可能破坏语句的字符的每个参数。如果(任何微小的)怀疑编码/转义参数,或者只是使用准备好的语句。

于 2012-08-24T12:25:37.677 回答