Skip to content

Commit

Permalink
Support of array binding in Query function
Browse files Browse the repository at this point in the history
  • Loading branch information
vlkolak committed Oct 18, 2017
1 parent 09ab320 commit b350034
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions src/AbstractMySqlGateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public function persist(EntityInterface ...$entities): bool
}

/**
* Perform a query
* Performs a query
*
* @param string|AbstractQuery $query
* @param \mysqli $link
Expand All @@ -205,23 +205,38 @@ public function query($query, \mysqli $link)

if ($query instanceof AbstractQuery) {
$sql = $query->getStatement();
foreach (array_keys($query->getBindValues()) as $name) {
$sql = preg_replace(sprintf('/:%s/U', $name), '?', $sql, 1);

foreach ($query->getBindValues() as $name => $bound) {
if (is_array($bound)) {
$sql = preg_replace(sprintf('/:%s/U', $name),
'(' . implode(',', array_fill(0, count($bound), '?')) .')',
$sql, 1);
} else {
$sql = preg_replace(sprintf('/:%s/U', $name), '?', $sql, 1);
}
}

$stmt = $link->prepare($sql);

if (!$stmt) {
throw new PrepareException(
sprintf('[%s] %s (%s)', $link->sqlstate, $link->error, (string) $sql),
$link->errno
);
}

$boundValues = $query->getBindValues();
$boundValues = [];
foreach ($query->getBindValues() as $name => $value) {
if (is_array($value)) {
foreach ($value as $valueIndex => $valueBind) {
$boundValues[$name . '_' . $valueIndex] = $valueBind;
}
} else {
$boundValues[$name] = $value;
}
}
if ($boundValues) {
$types = '';
foreach ($query->getBindValues() as $value) {
foreach ($boundValues as $value) {
if (is_bool($value)) {
$types .= 'i';
} elseif (is_int($value) || (is_string($value) && preg_match('/^(\d+)$/', $value))) {
Expand All @@ -232,7 +247,6 @@ public function query($query, \mysqli $link)
$types .= 's';
}
}

$stmt->bind_param($types, ...array_values($boundValues));
}

Expand All @@ -252,7 +266,6 @@ public function query($query, \mysqli $link)
$result->addEntities($this->entityFactory($row));
}
}

} else {
$data = $link->query($query);

Expand Down

0 comments on commit b350034

Please sign in to comment.