2 回答
TA贡献1859条经验 获得超6个赞
您也可以使用占位符。看下面的例子:
public function addUsersRoles(string $userKey, array $roles = []): bool
{
$values = [];
$inputParameters = [':user_key' => $userKey];
foreach ($roles as $index => $role) {
$rolePlaceholder = ':roleid' . $index;
$values[] = sprintf('(:user_key, %s)', $rolePlaceholder);
$inputParameters[$rolePlaceholder] = $role;
}
$sql = 'INSERT INTO user_roles (user_key, roleid) VALUES ';
$sql .= implode(', ', $values);
$db = static::getDB();
$stmt = $db->prepare($sql);
return $stmt->execute($inputParameters);
}
此代码将生成如下查询:
INSERT INTO user_roles (user_key, roleid) VALUES (:user_key, :roleid0), (:user_key, :roleid1), (:user_key, :roleid2), (:user_key, :roleid3), (:user_key, :roleid4);
$inputParameters 将是这样的:
[
':user_key' => 'some user key',
':roleid0' => 1,
':roleid1' => 2,
]
TA贡献1871条经验 获得超8个赞
count($roles)制作时不应该使用$in。它总是只是?, ?。对所有行重复该操作时,您只需要角色计数。您可以使用array_fill创建一个字符串数组(?, ?),然后implode在它们之间放置逗号。
您还需要插入创建具有交替键和角色的数组,并在执行时将其用作参数。
public function addUsersRoles($userkey, $roles = []){
$values = implode(',', array_fill(0, count($roles), '(?, ?)'));
$base_user_sql = 'INSERT user_roles (userkey, roleid) VALUES ';
$sql = $base_user_sql . $values;
$keys_and_roles = [];
foreach ($roles as $role) {
$keys_and_roles[] = $userkey;
$keys_and_roles[] = $role;
}
$db = static::getDB();
$stmt = $db->prepare($sql);
return $stmt->execute($keys_and_roles);
}
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报