现在我需要使用以下结构来处理将多个参数绑定到 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 以来,有了一个巨大的改进,可以解决这个问题。
要将任意数量的变量绑定到 mysqli 查询中,您将需要一个参数解包运算符 https://www.php.net/manual/en/functions.arguments.php#example-151。这将使操作尽可能简单和顺利。
例如,将 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)