如何使用 mysqli 准备语句绑定字符串数组?

问题描述 投票:0回答:7

我需要将一组值绑定到

WHERE IN(?)
子句。我该怎么做?

这有效:

$mysqli = new mysqli("localhost", "root", "root", "db");
if(!$mysqli || $mysqli->connect_errno)
{
    return;
}
$query_str = "SELECT name FROM table WHERE city IN ('Nashville','Knoxville')";
$query_prepared = $mysqli->stmt_init();
if($query_prepared && $query_prepared->prepare($query_str))
{
    $query_prepared->execute();

但是我无法像这样使用 bind_param

$query_str = "SELECT name FROM table WHERE city IN (?)";
$query_prepared = $mysqli->stmt_init();
if($query_prepared && $query_prepared->prepare($query_str))
{
    $cities = explode(",", $_GET['cities']);
    $str_get_cities = "'" . implode("', '", $get_cities) . "'"; // This equals 'Nashville','Knoxville'

    $query_prepared->bind_param("s", $cities);
    $query_prepared->execute();

我做错了什么?

我也试过

call_user_func_array
,但我似乎无法获得正确的语法。

php mysqli bindparam
7个回答
60
投票

来自我的文章,Mysqli 为 IN 子句准备了多个值的语句

PHP 8.2 方式。执行查询()

从 PHP 8.2 开始,您可以使用方便的函数execute_query()

// INSERT example
$sql = "INSERT INTO users (email, password) VALUES (?,?)"; // sql
$mysqli->execute_query($sql,[$email, $password]); // in one go

如果您的数组长度可变,则需要动态创建占位符列表

// WHERE IN example
$array = ['Nashville','Knoxville']; // our array
$parameters = str_repeat('?,', count($array) - 1) . '?'; // placeholders
$sql = "SELECT name FROM table WHERE city IN ($parameters)"; // sql
$result = $mysqli->execute_query($sql, $array); // in one go
$data = $result->fetch_all(MYSQLI_ASSOC); // fetch the data   

PHP 8.1 方式。数组到 execute()

从 PHP 8.1 开始,您可以直接传递一个数组来执行:

// INSERT example
$sql = "INSERT INTO users (email, password) VALUES (?,?)"; // sql
$stmt = $mysqli->prepare($sql); // prepare
$stmt->execute([$email, $password]); // execute with data! 

// WHERE IN example
$array = ['Nashville','Knoxville']; // our array
$parameters = str_repeat('?,', count($array) - 1) . '?'; // placeholders
$sql = "SELECT name FROM table WHERE city IN ($parameters)"; // sql
$stmt = $mysqli->prepare($sql); // prepare
$stmt->execute($array);
$result = $stmt->get_result(); // get the mysqli result
$data = $result->fetch_all(MYSQLI_ASSOC); // fetch the data   

旧版本,准备/绑定/执行方式

对于早期版本,任务更加复杂。

// INSERT example
$sql = "INSERT INTO users (email, password) VALUES (?,?)"; // sql
$data = [$email, $password]; // put your data into array
$stmt = $mysqli->prepare($sql); // prepare
$stmt->bind_param(str_repeat('s', count($data)), ...$data); // bind 
$stmt->execute();

虽然像您的情况一样,我们有任意数量的占位符,但我们将不得不添加更多代码。

  • 首先,我们需要创建一个字符串,其中的
    ?
    标记与数组中的元素数量一样多。为此,我们将使用
    str_repeat()
    功能,该功能非常方便。
  • 然后必须将这个带有逗号分隔问号的字符串添加到查询中。虽然它是一个变量,但在这种情况下它是安全的,因为它只包含常量值
  • 那么这个查询必须像任何其他查询一样准备
  • 然后我们需要创建一个字符串,其类型与 bind_param() 一起使用。请注意,通常没有理由对绑定变量使用不同的类型——mysql 会很乐意将它们全部作为字符串接受。有一些极端情况,但极为罕见。对于日常使用,您始终可以保持简单并使用“s”来表示所有内容。
    str_repeat()
    又来救援了。
  • 然后我们需要将我们的数组值绑定到语句。不幸的是,你不能把它写成一个单一的变量,像这样
    $stmt->bind_param("s", $array)
    ,在
    bind_param()
    中只允许标量变量。幸运的是,有一个argument unpacking operator完全可以满足我们的需求——将一组值发送到一个函数中,就好像它是一组不同的变量一样!
  • 剩下的和往常一样 - 执行查询,获取结果并获取数据!

所以正确的示例代码是

$array = ['Nashville','Knoxville']; // our array
$in    = str_repeat('?,', count($array) - 1) . '?'; // placeholders
$sql   = "SELECT name FROM table WHERE city IN ($in)"; // sql
$stmt  = $mysqli->prepare($sql); // prepare
$types = str_repeat('s', count($array)); //types
$stmt->bind_param($types, ...$array); // bind array at once
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$data = $result->fetch_all(MYSQLI_ASSOC); // fetch the data   

虽然这段代码相当大,但它比迄今为止本主题中提供的任何其他合理的解决方案都小得无法比拟。


13
投票

你不能用一个绑定两个变量问号

对于您绑定的每个变量,您需要一个问号

"bind_param" 检查每个变量是否符合要求。之后,字符串值放在引号之间。

这行不通:

"SELECT name FROM table WHERE city IN (?)"; ( becomes too )
$q_prepared->bind_param("s", $cities);
"SELECT name FROM table WHERE city IN ('city1,city2,city3,city4')";

必须是:

"SELECT name FROM table WHERE city IN (?,?,?,?)"; ( becomes too )
$q_prepared->bind_param("ssss", $city1, $city2, $city3, $city4);
"SELECT name FROM table WHERE city IN ('city1', 'city2', 'city3', 'city4')";

$query_prepared->bind_param
一个一个地引用字符串参数。 并且变量的数量和字符串类型的长度必须与语句中的参数匹配。

$query_str = "SELECT name FROM table WHERE city IN ('Nashville','Knoxville')";

会变成

$query_str = "SELECT name FROM table WHERE city IN (?,?)";

现在

bind_param
一定是

bind_param("ss", $arg1, $arg2)

有了这个

$query_str = "SELECT name FROM table WHERE city IN (?)";

bind_param

bind_param("s", $cities)

你得到:

$query_str = "SELECT name FROM table WHERE city IN ('Nashville,Knoxville')";

这就是数组不起作用的原因。这个事实的唯一解决方案是

call_user_func_array
.

如果你初始化一个语句,以下是不必要的:

$query_prepared = $mysqli->stmt_init();
if($query_prepared && $query_prepared->prepare($query_str)) {

这是正确的:

$query_prepared = $mysqli->stmt_init();
if($query_prepared->prepare($query_str)) {

如果你不想使用

call_user_func_array
并且你只有少量的参数,你可以用下面的代码来做。

[...]
$cities = explode(",", $_GET['cities']);
if (count($cities) > 3) { echo "too many arguments"; }
else
{
    $count = count($cities);
    $SetIn = "(";
    for($i = 0; $i < $count; ++$i)
    {
        $code .= 's';
        if ($i>0) {$SetIn.=",?";} else {$SetIn.="?";}
    }
    $SetIn .= ")";
    $query_str = "SELECT name FROM table WHERE city IN " . $SetIn;
    // With two arguments, $query_str will look like
    // SELECT name FROM table WHERE city IN (?,?)
    $query_prepared = $mysqli->stmt_init();
    if($query_prepared->prepare($query_str))
    {
        if ($count==1) { $query_prepared->bind_param($code, $cities[0]);}
        if ($count==2) { $query_prepared->bind_param($code, $cities[0], $cities[1]);}
        if ($count==3) { $query_prepared->bind_param($code, $cities[0], $cities[1], $cities[2]);
        // With two arguments, $query_prepared->bind_param() will look like
        // $query_prepared->bind_param("ss", $cities[0], $cities[1])
        }
        $query_prepared->execute();
    }
    [...]
}

我建议你用

call_user_func_array
试试看。

寻找

nick9v
的解决方案。

mysqli_stmt::bind_param


4
投票

从 PHP 8.1 版开始,不再需要绑定。与 5.0 版后的 PDO 一样,您现在可以将参数作为数组直接传递给 execute 方法

$mysqli       = new mysqli("localhost", "root", "root", "db");
$params       = ['Nashville','Knoxville'];
$placeholders = str_repeat('?,', count($params) - 1) . '?'
$query        = "SELECT name FROM table WHERE city IN ($placeholders)";
$stmt         = $mysqli->prepare($query);

$stmt->execute($params);

另一个例子,如果你有一个关联数组,其键与列名匹配:

$mysqli       = new mysqli("localhost", "root", "root", "db");
$data         = ["bar" => 23, "baz" => "some data"];
$params       = array_values($data);
$placeholders = str_repeat('?,', count($params) - 1) . '?'
$columns      = implode("`,`", array_keys($data));
$query        = "INSERT INTO foo (`$columns`) VALUES ($placeholders)";
$stmt         = $mysqli->prepare($query);

$stmt->execute($params);

另外值得一提的是,库现在默认在发生错误时抛出异常。在 8.1 版之前,情况并非如此。


4
投票

像这样使用call_user_func_array

$stmt = $mysqli->prepare("INSERT INTO t_file_result VALUES(?,?,?,?)");

$id = '1111';
$type = 2;
$result = 1;
$path = '/root';

$param = array('siis', &$id, &$type, &$result, &$path);
call_user_func_array(array($stmt, 'bind_param'), $param);

$stmt->execute();

printf("%d row inserted. \n", $stmt->effected_rows);
$stmt->close;

1
投票

我也遇到了这个问题,并在发现大多数人都在使用

call_user_func_array
之前与eval一起工作:

$fields = array('model', 'title', 'price'); // Fields in WHERE clause
$values = array( // Type and value for each field
    array('s', 'ABCD-1001'),
    array('s', '[CD] Test Title'),
    array('d', '16.00')
);
$sql = "SELECT * FROM products_info WHERE "; // Start of query
foreach ($fields as $current) { // Build where clause from fields
    $sql .= '`' . $current . '` = ? AND ';
}
$sql = rtrim($sql, 'AND '); // Remove last AND
$stmt = $db->prepare($sql);
$types = ''; $vals = '';
foreach ($values as $index => $current_val) { // Build type string and parameters
    $types .= $current_val[0];
    $vals .= '$values[' . $index . '][1],';
}
$vals = rtrim($vals, ','); // Remove last comma
$sql_stmt = '$stmt->bind_param("' . $types . '",' . $vals . ');'; // Put bind_param line together
eval($sql_stmt); // Execute bind_param
$stmt->execute();
$stmt->bind_result($col1, $col2, $col3, $col4, $col5, $col6); // This could probably also be done dynamically in the same way
while ($stmt->fetch()) {
    printf("%s %s %s %s %s %s\n", $col1, $col2, $col3, $col4, $col5, $col6);
}

0
投票

php 8.2 使用 execute_query 解决了所有问题

$this->execute_query($query, $parms);

喜欢

$query = "SELECT * FROM users WHERE `email` IN (?) LIMIT 1";
$parms = ["[email protected]"];
$this->execute_query($query, $parms);

还记得吗?是占位符和数量? (占位符)与 count($parms) 相同,可以通过多种方式完成。

所以在你的情况下应该是 would

$query = "SELECT name FROM table WHERE city IN (? , ?)";
$parms = ['Nashville','Knoxville'];
$this->execute_query($query, $parms);

https://www.php.net/manual/en/mysqli.execute-query

如果你想先创建动态$query,那么

$query = "SELECT name FROM table WHERE city IN (".implode(",",array_map(fn()=>"?",$parms)).")";

-1
投票

我这样做的方式:准备查询及其所有单独的问号,以及类型字符串。

$cities = array('Nashville', 'Knoxville');
$dibs = '';
$query = "SELECT name FROM table WHERE city IN (";
$marks = array();

foreach ($cities as $k => $city) {
    // i, s, b, d type based on the variables to bind.
    $dibs .= 's';
    array_push($marks, '?');
}

$query .= implode(',', $marks) . ')';

连接。

$mysql = new mysqli($host, $user, $pass, $dbname);
$statement =
    $mysql->prepare($query)
OR    die(sprintf(
        'Query error (%s) %s', $mysql->errno, $mysql->error
    ))
;

然后使用“...”标记/省略号(文档)来绑定数组。

if ($statement) {
    $statement->bind_param($dibs, ...$cities);
    $statement->execute();

    $statement->close();
}
$mysql->close();

我知道它有点违背为了逃避而绑定的目的(但至少它适用于整数列表,即 ID)。

© www.soinside.com 2019 - 2024. All rights reserved.