【问题标题】:Bind multiple parameters into mysqli query将多个参数绑定到mysqli查询中
【发布时间】:2013-07-26 02:41:43
【问题描述】:

现在我需要使用以下结构来处理将多个参数绑定到 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

【问题讨论】:

    标签: php mysqli bindparam


    【解决方案1】:

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

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

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

    // 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   
    

    【讨论】:

    • 非常感谢 - 我真的对我对这个问题的丑陋解决方案感到绝望。我同意错误报告是我的一个弱点,我需要花时间了解更多信息。我像 2 个月前才学过 php,所以到现在为止,一切都是为了尽可能多地做。现在我想我可能必须更多地专注于尽可能做好事情!拥抱和感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2016-02-14
    • 1970-01-01
    相关资源
    最近更新 更多