Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
2026-11-25 (4.0.11)
* Security: Statement::bStrArr() now binds each value as its own parameter. Before, values were pasted into the SQL unescaped, so a value containing a quote could change the query (SQL injection).
* The binding-layer bStrArr() methods are deprecated; Statement no longer calls them.
* Statement::getComputed() now fills raw (%%) placeholders before named ones, matching execute().
* bInt() no longer formats values as unsigned: negative numbers kept their sign wrong (bInt(-5) bound 9223372036854775807). Values outside the integer range, INF and NAN now throw InvalidArgumentException.

2026-11-25 (4.0.10)
* Added GitHub Actions CI: PHPUnit on PHP 8.1-8.5 against MySQL 8.4, plus PHPStan (level 8) and PSR-12 checks.
* Upgraded PHPStan to 2.x and fixed the issues it found (redundant checks, bFloat() return type).
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ GeekLab\GLPDO2
Easy to use PDO Wrapper for PHP >= 8.1

### Latest
2022-11-25 (4.0.9)
* Style fixes.
2026-11-25 (4.0.11)
* Security: `bStrArr()` now binds each value as a parameter. Values containing quotes could previously break out of the `IN()` list (SQL injection).
* `bInt()` no longer turns negative numbers into huge positive ones, and rejects values outside the integer range.

### Features
* Bind value by the correct type. E.g. Don't bind as a string where an integer bind should be.
Expand Down Expand Up @@ -78,7 +79,7 @@ Statement->bFloat($value, optional integer $decimals, optional boolean $null)<br
Binds a value aa a float, with decimal place (default of 3) and optional NULL return. Use '%%' instead of '?'.

Statement->bInt($value, optional boolean $null)<br/>
Bind a value as an integer, whith optional NULL return.
Binds a value as an integer, with optional NULL return. Floats are truncated toward zero. Throws InvalidArgumentException for values outside the integer range.

Statement->bIntArray(array $data, integer $default)<br/>
Converts an array of integers to a comma separated values. Will output $default (which is 0) if $data is not an array. Used with IN() statements. Use '%%' instead of '?'.
Expand All @@ -93,7 +94,7 @@ Statement->bStr($value, optional boolean $null, optional \PDO::PARAM_* $type)<br
Binds a value as a string, with optional NULL value return and optional PDO binding type (default \PDO::PARAM_STR).

Statement->bStrArr(array $values, optional string $default)<br/>
Binds a string converted array for use with IN statements. $default is used when value isn't an array, which the default is NULL. Use '%%' instead of '?'.
Binds an array of strings for use with IN() statements. Each value is bound as its own parameter. Use '%%' instead of '?'. If $values is empty, $default (an empty string by default) is inserted raw, unquoted and unescaped, so never pass untrusted input as $default.

Statement->bind($name, $value, \PDO::PARAM_* $type)<br/>
Binds a value to a named parameter with option PDO binding type (default \PDO::PARAM_STR)
Expand Down
3 changes: 3 additions & 0 deletions src/Bindings/Bindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ public function bStr(
* @param float | bool | int | string $default
*
* @return array{float | bool | int | string}
*
* @deprecated 4.0.11 Statement::bStrArr() no longer calls this; it binds each value as a parameter.
* This method pastes the values into the SQL unescaped, so never use it with untrusted input.
*/
public function bStrArr(array $values, float | bool | int | string $default = ''): array
{
Expand Down
3 changes: 3 additions & 0 deletions src/Bindings/MySQL/MySQLStringBindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ public function bStr(
* @param float | bool | int | string $default
*
* @return array{float | bool | int | string}
*
* @deprecated 4.0.11 Statement::bStrArr() no longer calls this; it binds each value as a parameter.
* This method pastes the values into the SQL unescaped, so never use it with untrusted input.
*/
public function bStrArr(array $values, float | bool | int | string $default = ''): array
{
Expand Down
3 changes: 3 additions & 0 deletions src/Bindings/StringBindingInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ public function bStr(
* @param float | bool | int | string $default
*
* @return array{float | bool | int | string}
*
* @deprecated 4.0.11 Statement::bStrArr() no longer calls this; it binds each value as a parameter.
* This method pastes the values into the SQL unescaped, so never use it with untrusted input.
*/
public function bStrArr(array $values, float | bool | int | string $default = ''): array;
}
39 changes: 33 additions & 6 deletions src/Statement.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PDO;
use PDOStatement;
use Exception;
use InvalidArgumentException;
use GeekLab\GLPDO2\Bindings\Bindings;

class Statement
Expand All @@ -25,6 +26,7 @@ class Statement
*/
private array $rawNamed = []; // Raw named placeholders.
private int $rawPos = 0; // Position holder for raw statement processing.
private int $arrPos = 0; // Position holder for array element binds (bStrArr).
// /**
// * @var array{} | array{mixed} $rawSql
// */
Expand Down Expand Up @@ -243,18 +245,40 @@ public function bLike(string $value, bool $ends = false, bool $starts = false):
}

/**
* Convert an array into a string and bind it.
* Great for IN() statements.
* Bind an array of strings for IN() statements. Uses %%
* Each value is bound as its own parameter, so values are never pasted into the SQL.
* If $values is empty, $default is inserted raw (unquoted and unescaped) instead.
*
* @param array{} | array{mixed} $values
* @param float | bool | int | string $default
*
* @return Statement
* @throws InvalidArgumentException
*/
public function bStrArr(array $values, float | bool | int | string $default = ''): self
{
$binding = $this->bindings->bStrArr($values, $default);
$this->rawBind($this->getNextName('raw'), $binding[0]);
if (empty($values)) {
$this->rawBind($this->getNextName('raw'), $default);

return $this;
}

$names = [];

foreach ($values as $value) {
if ($value !== null && !is_scalar($value)) {
throw new InvalidArgumentException('Can not bind a non-scalar value in a string array.');
}

// NULL becomes an empty string, as it did when the values were imploded.
$binding = $this->bindings->bStr($value ?? '');
$name = $this->getNextName('arr');
$this->bind($name, $binding[0], $binding[1]);
$names[] = $name;
}

// The %% placeholder becomes a list of named placeholders, e.g. ":arr0, :arr1".
$this->rawBind($this->getNextName('raw'), implode(', ', $names));

return $this;
}
Expand Down Expand Up @@ -311,6 +335,7 @@ private function getNextName(string $type = 'bind'): string
'sql' => sprintf(':pos%d', $this->sqlPos++),
'rawSql' => sprintf(':raw%d', $this->rawPos),
'raw' => sprintf(':raw%d', $this->rawPos++),
'arr' => sprintf(':arr%d', $this->arrPos++),
default => sprintf(':pos%d', $this->bindPos++),
};
}
Expand Down Expand Up @@ -452,6 +477,7 @@ public function reset(): self
$this->sqlPos = 0;
$this->rawNamed = [];
$this->rawPos = 0;
$this->arrPos = 0;
// $this->rawSql = [];

return $this;
Expand All @@ -466,8 +492,9 @@ public function reset(): self
*/
public function getComputed(): string
{
// Merge SQL together
$sql = implode("\n", $this->SQL);
// Merge SQL together, then fill raw placeholders first, as execute() does.
// Raw values can contain named placeholders (bStrArr), which are filled below.
$sql = $this->rawPlaceholderFill(implode("\n", $this->SQL));

// Replace positioned placeholders with named placeholders (first value).
// Force to string, in the case of null.
Expand Down
78 changes: 78 additions & 0 deletions tests/GLPDO2MySQLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,84 @@ public function testStringArray(): void
$this->assertEquals($expected, $this->db->selectRows($Statement));
}

/**
* Values are bound as parameters, so a quote can't break out of the IN() list.
*
* @return void
* @throws Exception
*/
public function testStringArrayIsNotInjectable(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$Statement
->sql('SELECT `name`')
->sql('FROM `test`')
->sql('WHERE `location` IN (%%)')->bStrArr(['Estonia', "x') OR ('1'='1"])
->sql('ORDER BY `id`;');

$this->assertEquals([['name' => 'Reese']], $this->db->selectRows($Statement));
}

/**
* Array placeholders must not shift the positions of '?' placeholders around them.
*
* @return void
* @throws Exception
*/
public function testStringArrayWithPositionalPlaceholders(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$Statement
->sql('SELECT `name`')
->sql('FROM `test`')
->sql('WHERE `id` > ?')->bInt(1)
->sql('AND `location` IN (%%)')->bStrArr(['Germany', 'USA'])
->sql('AND `id` < ?')->bInt(4)
->sql('ORDER BY `id`;');

$expected = "SELECT `name`\n" .
"FROM `test`\n" .
"WHERE `id` > 1\n" .
"AND `location` IN ('Germany', 'USA')\n" .
"AND `id` < 4\n" .
"ORDER BY `id`;";

$this->assertEquals($expected, $Statement->getComputed());
$this->assertEquals([['name' => 'Hyacinth'], ['name' => 'Quynn']], $this->db->selectRows($Statement));
}

/**
* An empty array inserts $default raw, as before.
*
* @return void
* @throws Exception
*/
public function testStringArrayEmptyUsesDefault(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$Statement
->sql('SELECT `name`')
->sql('FROM `test`')
->sql('WHERE `location` IN (%%);')->bStrArr([], 'NULL');

$this->assertEquals("SELECT `name`\nFROM `test`\nWHERE `location` IN (NULL);", $Statement->getComputed());
$this->assertEquals([], $this->db->selectRows($Statement));
}

/**
* @return void
*/
public function testStringArrayNonScalarException(): void
{
$this->expectException(\InvalidArgumentException::class);

$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());
$Statement->sql('SELECT 1 WHERE `location` IN (%%);')->bStrArr(['Germany', ['nested']]);
}

// Insert

/**
Expand Down
Loading