Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将多个参数绑定到mysqli查询中_Php_Mysqli_Bindparam - Fatal编程技术网

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 .= "?,";
    }
}
我的问题是,一定有一种方法可以动态地处理查询中所需的尽可能多的输入。硬编码bind_参数似乎是一种非常糟糕的处理方法


我使用的是php版本5.4.10,不幸的是,默认情况下,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   

非常感谢这一点——我真的对我丑陋的解决方案感到绝望。我同意错误报告是我的一个弱点,我需要花时间来了解更多。我只是在两个月前才学会php,所以到现在为止,我都在尽可能多地学习php。现在我想我应该把更多的精力放在尽可能好的做事上!!拥抱,谢谢!