我可以绑定(bind) int
、str
、bool
和 null
类型的值,但我不能绑定(bind)数组类型。
我已经尝试了这两个函数,即 bindValue
和 bindParam
但它们都不起作用。
我怎样才能做到这一点?
// a helper function to map Sqlite data type
function getArgType($arg) {
switch (gettype($arg)) {
case 'double': return SQLITE3_FLOAT;
case 'integer': return SQLITE3_INTEGER;
case 'boolean': return SQLITE3_INTEGER;
case 'NULL': return SQLITE3_NULL;
case 'string': return SQLITE3_TEXT;
default:
throw new \InvalidArgumentException('Argument is of invalid type '.gettype($arg));
}
}
$sql = "SELECT * FROM table_name WHERE id IN (?)";
$params = [[10, 9, 6]]; // array of array
$dbpath = '/path/to/sqlite.sqlite';
$db = new SQLite3($dbPath, SQLITE3_OPEN_READONLY);
$stmt = $db->prepare($sql);
try {
foreach ($params as $index => $val) {
if (is_array($val)) {
/************* I am stuck here *************/
$ok = $stmt->bindParam($index + 1, $val);
// Using bindValue also didn't worked!
} else {
$ok = $stmt->bindValue($index + 1, $val, getArgType($val));
}
if (!$ok) {
throw new Exception("Unable to bind param: $val");
}
}
} catch (Exception $ex) {
// NO exception is thrown from bindValue() or bindParam()
$reason = "Error in binding statement. " . $ex->getMessage();
die($reason);
}
$result = $stmt->execute();
$data = [];
while ($row = $result->fetchArray($mode)) {
$data[] = $row;
}
var_dump($data);
编辑: 我已经尝试用参数数组中所需数量的问号替换单个 ?
,但只有当我的数组少于 时它才有效1000 值!我认为这是在 PHP 的 SQLite3 中准备语句的方式的限制。
最佳答案
不幸的是,这不可能!您不能绑定(bind)数组。
针对您的问题,最简单的解决方案如下:
- 为数组中的每个值创建一个占位符 (
?
) 的 SQL 查询 - 通过遍历数组来绑定(bind)每个值。
但还有其他选择(例如子 SELECT)
More information here (即使是 Java 问题,也几乎是相同的主题/问题,因为在这种情况下数据库类型无关紧要)
编辑: 通常,绑定(bind)参数的 SQL 限制设置为 999
,但您 can change it if you need to .
关于PHP - 如何在准备好的语句中将数组替换为主机参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36586852/