Created
May 14, 2017 21:54
-
-
Save voronkovich/e72cfd6206dec800ca533d9fcd61bfbb to your computer and use it in GitHub Desktop.
db_get_prepare_stmt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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