【问题标题】:Prepared statement when the SQL statement is not the same all the timeSQL 语句一直不一样时的预处理语句
【发布时间】:2022-01-09 02:46:27
【问题描述】:

我有以下代码,SQL 语句会根据用户在表单中选择的选项而变化。

    $sql = "SELECT * FROM products";

if ($valueone !== "all") {
    $sql .= " WHERE brand = ? ";
}
if ($valuetwo !== "all") {
    if (strpos($sql, "WHERE") !== false) { 
        $sql .= " AND category = ? ";
    } 
    else {
        $sql .= " WHERE category = ? ";
    }
}
if ($valuethree !== "all") {
    if (strpos($sql, "WHERE") !== false) { 
        $sql .= " AND third = ? ";
    } 
    else {
        $sql .= " WHERE third = ? ";
    }
}

$sql .= " ORDER BY rand();";

$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    header("location: error.php?sql");
    die(); 
}

mysqli_stmt_bind_param($stmt, "sss", $valueone, $valuetwo, $valuethree);
mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

mysqli_stmt_close($stmt);

$count = mysqli_num_rows($result);

现在,我显然想用准备好的陈述来保护自己,但我该怎么做呢?因为它不会一直是三个“S”,有时根本不是。

我希望你能看到我在做什么!

【问题讨论】:

标签: php sql prepared-statement


【解决方案1】:

您可以将其与 sql 一起构建,而不是硬编码“sss”。举个例子

if ($valueone !== "all") {
    $sql .= " WHERE brand = ? ";
    $types .= "s"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    相关资源
    最近更新 更多