Skip to content

Instantly share code, notes, and snippets.

@voronkovich
Created May 14, 2017 21:54
Show Gist options
  • Save voronkovich/e72cfd6206dec800ca533d9fcd61bfbb to your computer and use it in GitHub Desktop.
Save voronkovich/e72cfd6206dec800ca533d9fcd61bfbb to your computer and use it in GitHub Desktop.
db_get_prepare_stmt
<?php
/**
* Создает подготовленное выражение на основе готового SQL запроса и переданных данных.
*
* @param mysqli $link Ресурс соединения
* @param string $sql SQL запрос с плейсхолдерами вместо значений
* @param array $data Данные для вставки на место плейсхолдеров
*
* @throws \UnexpectedValueException Если тип параметра не поддерживается
*
* @return mysqli_stmt Подготовленное выражение
*/
function db_get_prepare_stmt(mysqli $link, string $sql, array $data = [])
{
$stmt = mysqli_prepare($link, $sql);
if (empty($data)) {
return $stmt;
}
static $allowed_types = [
'integer' => 'i',
'double' => 'd',
'string' => 's',
];
$types = '';
$stmt_data = [];
foreach ($data as $value) {
$type = gettype($value);
if (!isset($allowed_types[$type])) {
throw new \UnexpectedValueException(sprintf('Unexpected parameter type "%s".', $type));
}
$types .= $allowed_types[$type];
$stmt_data[] = $value;
}
mysqli_stmt_bind_param($stmt, $types, ...$stmt_data);
return $stmt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment