如何使用 mysqli API 制作完全动态的准备语句?

Kir*_*ito 5 php mysqli prepared-statement

我需要更改此查询以使用准备好的语句。是否可以?

查询:

$sql = "SELECT id, title, content, priority, date, delivery FROM tasks " . $op . " " . $title . " " . $content . " " . $priority . " " . $date . " " . $delivery . " ORDER BY " . $orderField . " " . $order . " " . $pagination . "";
Run Code Online (Sandbox Code Playgroud)

在查询之前,有代码检查 POST 变量并更改查询中变量的内容。

//For $op makes an INNER JOIN with or without IN clause depending on the content of a $_POST variable
$op = "INNER JOIN ... WHERE opID  IN ('"$.opID."')";
//Or
$op = "INNER JOIN ... ";

//For $title (depends of $op):
$title = "WHERE title LIKE'%".$_POST["title"]."%'";
//Or
$title = "AND title LIKE'%".$_POST["title"]."%'";

//For $content:
$content = "AND content LIKE '%".$_POST["content"]."%'";

//For $priority just a switch:
$priority = "AND priority = DEPENDING_CASE";

//For $date and $delivery another switch 
$d = date("Y-m-d", strtotime($_POST["date"]));
$date = "AND date >= '$d' 00:00:00 AND date <= '$d' 23:59:59";
//Or $date = "AND date >= '$d' 00:00:00";
//Or $date = "AND date <= '$d' 23:59:59";

//For $orderField
$orderField = $_POST["column"];

//For $order
$order= $_POST["order"];

//For $pagination 
$pagination = "LIMIT ".$offset.",". $recordsPerPage;
Run Code Online (Sandbox Code Playgroud)

我如何使用准备好的语句来执行此查询?

  • 查询可以更加静态,但这意味着要制作不同的准备好的语句并根据 $_POST 检查来执行它。
  • 它取决于许多变量,因为此查询在包含搜索字段和要排序的列的表中显示结果。

查询的完整示例如下(取决于 $_POST 检查):

SELECT id, title, content, priority, date, delivery FROM tasks INNER JOIN op ON task.op = op.opId WHERE op IN (4851,8965,78562) AND title LIKE '%PHT%' AND content LIKE '%%' AND priority = '2' ORDER BY date DESC LIMIT 0, 10 
Run Code Online (Sandbox Code Playgroud)

You*_*nse 5

这是一个很好的问题。感谢您转向准备好的发言。看来经过这么多年的奋斗,这个想法终于开始占据主导地位。

免责声明:将会有指向我自己网站的链接,因为我已经帮助人们使用 PHP 20 多年了,并且痴迷于撰写有关最常见问题的文章。

是的,这是完全可能的。查看我的文章如何为 mysqli 创建搜索过滤器以获得功能齐全的示例。

对于这一WHERE部分,您所需要做的就是创建两个单独的数组 - 一个包含带有占位符的查询条件,另一个包含这些占位符的实际值,即:

WHERE条款

$conditions = [];
$parameters = [];

if (!empty($_POST["content"])) {
    $conditions[] = 'content LIKE ?';
    $parameters[] = '%'.$_POST['content ']."%";
}
Run Code Online (Sandbox Code Playgroud)

等等,适用于所有搜索条件。

然后你可以implode 使用字符串作为粘合的所有条件AND,并得到一个一流的WHERE子句:

if ($conditions)
{
    $where .= " WHERE ".implode(" AND ", $conditions);
}
Run Code Online (Sandbox Code Playgroud)

所有搜索条件的例程都是相同的,但子句的例程会略有不同 IN()

IN()条款

有点不同,因为您需要添加更多占位符和更多值:

if (!empty($_POST["opID"])) {
    $in  = str_repeat('?,', count($array) - 1) . '?';
    $conditions[] = "opID IN ($in)";
    $parameters = array_merge($parameters, $_POST["opID"]);
}
Run Code Online (Sandbox Code Playgroud)

此代码将向子句添加与 中的元素一样多的?占位符,并将所有这些值添加到数组中。可以在我网站同一部分的相邻文章中找到相关解释。IN()$_POST["opID"]$parameters

完成 withWHERE子句后,您可以转到查询的其余部分

ORDER BY条款

您不能参数化 order by 子句,因为字段名称和 SQL 关键字不能用占位符表示。为了解决这个问题,我请求您使用我为此目的编写的白名单函数。有了它,您可以使您的 ORDER BY 子句 100% 安全但非常灵活。您所需要的只是预定义一个数组,其中包含 order by 子句中允许的字段名称:

$sortColumns = ["title","content","priority"]; // add your own
Run Code Online (Sandbox Code Playgroud)

然后使用这个方便的函数获取安全值:

$orderField = white_list($_POST["column"], $sortColumns, "Invalid column name");
$order = white_list($_POST["order"], ["ASC","DESC"], "Invalid ORDER BY direction");
Run Code Online (Sandbox Code Playgroud)

这是一个智能功能,涵盖了三种不同的场景

  • 如果未提供任何值(即 $_POST["column"] 为空),将使用白名单中的第一个值,因此它作为默认值
  • 如果提供了正确的值,它将在查询中使用
  • 如果提供了不正确的值,则会抛出错误。

LIMIT条款

LIMIT值是完美参数化的,因此您只需将它们添加到$parameters数组中即可:

$limit = "LIMIT ?, ?";
$parameters[] = $offset;
$parameters[] = $recordsPerPage;
Run Code Online (Sandbox Code Playgroud)

最后组装

最后,你的查询将是这样的

$sql = "SELECT id, title, content, priority, date, delivery 
        FROM tasks INNER JOIN ... $where ORDER BY `$orderField` $order $limit"; 
Run Code Online (Sandbox Code Playgroud)

并且可以使用下面的代码来执行

$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
Run Code Online (Sandbox Code Playgroud)

其中$data是一个常规数组,包含查询返回的所有行。