php - 将多个参数绑定(bind)到 mysqli 查询中

标签 php mysqli bindparam

现在我需要使用以下结构来处理将多个参数绑定(bind)到 mysqli 查询中:

if ($words_total == 1)
{
    $statement -> bind_param("s", $words[0]);
}
else if ($words_total == 2)
{
    $statement -> bind_param("ss", $words[0], $words[1]);
}
else if ($words_total == 3)
{
    $statement -> bind_param("sss", $words[0], $words[1], $words[2]);
}

//and so on....

我使用下面的代码计算出问号的数量并将其插入到我的查询中:

$marks = "";
for($i = 1; $i<=$words_total; $i++) {
    if ($i == $words_total)
    {
        $marks .= "?";
    }
    else
    {
        $marks .= "?,";
    }
}

我的问题是肯定有一种方法可以根据我的需要动态地处理尽可能多的查询输入。对 bind_param() 进行硬编码似乎是一种非常糟糕的处理方式。

我使用的 php 版本是 5.4.10

最佳答案

不幸的是,默认情况下,bind_param() 不接受数组而不是单独的变量。然而,自 PHP 5.6 以来,有一个巨大的改进可以解决这个问题。

要将任意数量的变量绑定(bind)到 mysqli 查询中,您需要 argument unpacking operator .它将使操作尽可能简单和流畅。

例如,要将 PHP 数组与 mysql 的 IN() 运算符一起使用,您将需要以下代码

// our array
$array = ['a','b','c']; 

// create an SQL query with placeholders and prepare it
$in    = str_repeat('?,', count($array) - 1) . '?'; //  returns ?,?,?...
$sql   = "SELECT name FROM table WHERE city IN ($in)"; 
$stmt  = $mysqli->prepare($sql);

// create the types string dynamically and bind an array
$types = str_repeat('s', count($array)); // returns sss...
$stmt->bind_param($types, ...$array); 

// execute and fetch the rows
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$data = $result->fetch_all(MYSQLI_ASSOC); // fetch the data   

关于php - 将多个参数绑定(bind)到 mysqli 查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61837968/

相关文章:

PHP 更新查询不起作用

php - GROUP BY 中使用的传入参数仍然返回 1 行?

php - 如何使用php+Mysql更新列表状态一次

php - 如何声明函数的日期特定值

php - 复杂的SQL函数, 'Syntax error or access violation: 1065 Query was empty'

php - 如何为更新查询准备语句?

PHP -> 如何在注册查询中绑定(bind)多个值?

php - 使用 PHP/PDO 将 SQL 脚本运行到 PostgreSQL

php - 拉维尔 4.2 : How to use whereIn() and with() to get a list of items in a one-to-many relationship?

PHP mysqli 列表框