Php 将多个参数绑定到mysqli查询中

Php 将多个参数绑定到mysqli查询中,php,mysqli,bindparam,Php,Mysqli,Bindparam,现在,我需要使用以下结构来处理将多个参数绑定到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

现在,我需要使用以下结构来处理将多个参数绑定到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 .= "?,";
    }
}
$marks=”“;

对于($i=1;$i),不幸的是,默认情况下,bind_param()不接受数组而不是单独的变量。然而,由于PHP5.6,有一个巨大的改进可以实现这一目的

要将任意数量的变量绑定到mysqli查询中,您需要一个新的变量。它将使操作尽可能简单和顺利

例如,要使用带有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   

不幸的是,默认情况下,bind_param()不接受数组而不是单独的变量

要将任意数量的变量绑定到mysqli查询中,您需要一个新的变量。它将使操作尽可能简单和顺利

例如,要使用带有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,所以到目前为止,所有的一切都是为了能够做尽可能多的事情。现在我想我应该更多地关注doi尽可能把事情做好!!拥抱并感谢!非常感谢这一点-我对这个问题丑陋的解决方案感到绝望。我同意错误报告是我的一个弱点,我需要花时间去了解更多。我只在两个月前才学会了php,所以到目前为止,一切都是为了尽可能多地去做e、 现在我想我应该把更多的精力放在尽可能好的做事上!!拥抱和感谢!