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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
2026-11-25 (4.0.12)
* Statement::sql() no longer turns '?' and '%%' inside quoted strings or comments into placeholders, so SQL like `WHERE note = 'Why?'` works. Inside backtick identifiers, '%%' is still a placeholder so `%%` with bRaw() can name a table.
* Two '%%' placeholders in one sql() call now each get their own value. Before, both got the first one: sql('VALUES (%%, %%)')->bFloat(1)->bFloat(2) produced VALUES (1.000, 1.000).
* Statement::execute() joins sql() calls with newlines, as getComputed() already did, so a "-- comment" in one call no longer comments out the calls after it.

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.
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ GeekLab\GLPDO2
Easy to use PDO Wrapper for PHP >= 8.1

### Latest
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.
2026-11-25 (4.0.12)
* `?` and `%%` inside quoted strings and comments are no longer treated as placeholders, so SQL like `WHERE note = 'Why?'` works.
* Two `%%` placeholders in one `sql()` call now each get their own value.
* A `-- comment` in one `sql()` call no longer comments out the calls after it.

### 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 @@ -135,7 +136,7 @@ Is there a transaction in progress, returns bool.

### Misc Methods
Statement->sql(string $text)<br/>
Used to build up the SQL parameterized statement.
Used to build up the SQL parameterized statement. Each call is one line of the statement. '?' and '%%' are placeholders only in SQL code: inside quoted strings ('...', "...") and comments (-- , #, /* */) they are left as plain text, and inside backtick identifiers only '%%' is a placeholder (for table names with bRaw()).

Statement->reset()<br/>
Used to reset Statement private variables. Usefully for creating multiple queries without having to create a new Statement object.
Expand Down
133 changes: 111 additions & 22 deletions src/Statement.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,18 @@ class Statement
* @var array{} | array<int|string, mixed> $rawNamed
*/
private array $rawNamed = []; // Raw named placeholders.
private int $rawPos = 0; // Position holder for raw statement processing.
private int $rawPos = 0; // Position for raw binds (bRaw, bFloat, bIntArray, bStrArr).
private int $rawSqlPos = 0; // Position holder for '%%' placeholders found by sql().
private int $arrPos = 0; // Position holder for array element binds (bStrArr).

// Where sql() is in the statement text, so '?' and '%%' inside literals and comments are left alone.
// Kept across sql() calls, since a quoted string can span several of them.
private const LEX_CODE = 0;
private const LEX_QUOTED = 1; // Inside '...', "..." or `...`; $lexQuote holds which.
private const LEX_LINE_COMMENT = 2; // After "-- " or "#", until the end of the line.
private const LEX_BLOCK_COMMENT = 3; // Inside /* ... */.
private int $lexState = self::LEX_CODE;
private string $lexQuote = '';
// /**
// * @var array{} | array{mixed} $rawSql
// */
Expand Down Expand Up @@ -333,7 +343,8 @@ private function getNextName(string $type = 'bind'): string
{
return match ($type) {
'sql' => sprintf(':pos%d', $this->sqlPos++),
'rawSql' => sprintf(':raw%d', $this->rawPos),
// Each '%%' gets its own number, matched in order to the raw binds, as '?' is to binds.
'rawSql' => sprintf(':raw%d', $this->rawSqlPos++),
'raw' => sprintf(':raw%d', $this->rawPos++),
'arr' => sprintf(':arr%d', $this->arrPos++),
default => sprintf(':pos%d', $this->bindPos++),
Expand All @@ -350,9 +361,9 @@ private function getNextName(string $type = 'bind'): string
*/
public function execute(PDO $PDO): PDOStatement
{
// Prepare the SQL, force to string in case of null.
// Then replace raw placements with raw values.
$sql = $this->rawPlaceholderFill(implode(' ', $this->SQL));
// Join the sql() calls one per line, as getComputed() does, so a "-- comment" in one call
// doesn't swallow the calls after it. Then replace raw placements with raw values.
$sql = $this->rawPlaceholderFill(implode("\n", $this->SQL));

/** @var PDOStatement $stmt */
$stmt = $PDO->prepare($sql);
Expand Down Expand Up @@ -434,36 +445,111 @@ private function placeholderGetName(): string

/**
* Builds up the SQL parameterized statement.
* '?' becomes a named placeholder and '%%' a raw placeholder, except inside
* quoted strings ('...', "...") and comments (-- , #, /* * /).
* Inside backtick identifiers only '%%' is a placeholder, so `%%` with bRaw() can name a table.
*
* @param string $text
*
* @return Statement
*/
public function sql(string $text): self
{
// Replace positioned placeholders with named placeholders (first value).
// Force to string, in the case of null.
$text = (string)preg_replace_callback(
'/\?/m',
function () {
return $this->placeholderGetName();
},
$text
);
$out = '';
$len = strlen($text);

for ($i = 0; $i < $len; $i++) {
$char = $text[$i];
$next = $i + 1 < $len ? $text[$i + 1] : '';

switch ($this->lexState) {
case self::LEX_QUOTED:
if ($this->lexQuote === '`' && $char === '%' && $next === '%') {
// `%%` with bRaw() fills in an identifier, such as a table name.
$out .= $this->getNextName('rawSql');
$i++;
continue 2;
}

if ($char === '\\' && $this->lexQuote !== '`') {
// Backslash escape: copy it and the escaped character as is.
$out .= $char . $next;
$i++;
continue 2;
}

if ($char === $this->lexQuote) {
// A doubled quote ('') closes and immediately reopens, which works out the same.
$this->lexState = self::LEX_CODE;
}
break;

$text = (string)preg_replace_callback(
'/%%/m',
function () {
return $this->getNextName('rawSql');
},
$text
);
case self::LEX_LINE_COMMENT:
if ($char === "\n") {
$this->lexState = self::LEX_CODE;
}
break;

$this->SQL[] = $text;
case self::LEX_BLOCK_COMMENT:
if ($char === '*' && $next === '/') {
$out .= '*/';
$i++;
$this->lexState = self::LEX_CODE;
continue 2;
}
break;

default:
if ($char === '?') {
$out .= $this->placeholderGetName();
continue 2;
}

if ($char === '%' && $next === '%') {
$out .= $this->getNextName('rawSql');
$i++;
continue 2;
}

if ($char === "'" || $char === '"' || $char === '`') {
$this->lexState = self::LEX_QUOTED;
$this->lexQuote = $char;
} elseif ($char === '#' || ($char === '-' && $next === '-' && $this->isCommentGap($text, $i + 2))) {
$this->lexState = self::LEX_LINE_COMMENT;
} elseif ($char === '/' && $next === '*') {
$out .= '/*';
$i++;
$this->lexState = self::LEX_BLOCK_COMMENT;
continue 2;
}
}

$out .= $char;
}

// Each sql() call is its own line in getComputed(), so a line comment ends with it.
if ($this->lexState === self::LEX_LINE_COMMENT) {
$this->lexState = self::LEX_CODE;
}

$this->SQL[] = $out;

return $this;
}

/**
* MySQL only treats "--" as a comment when whitespace (or the end of the text) follows it.
*
* @param string $text
* @param int $pos position just after "--"
*
* @return bool
*/
private function isCommentGap(string $text, int $pos): bool
{
return $pos >= strlen($text) || in_array($text[$pos], [' ', "\t", "\r", "\n"], true);
}

/**
* Reset / Clear out properties.
*
Expand All @@ -477,7 +563,10 @@ public function reset(): self
$this->sqlPos = 0;
$this->rawNamed = [];
$this->rawPos = 0;
$this->rawSqlPos = 0;
$this->arrPos = 0;
$this->lexState = self::LEX_CODE;
$this->lexQuote = '';
// $this->rawSql = [];

return $this;
Expand Down
48 changes: 48 additions & 0 deletions tests/GLPDO2MySQLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,54 @@ public function testStringArrayNonScalarException(): void
$Statement->sql('SELECT 1 WHERE `location` IN (%%);')->bStrArr(['Germany', ['nested']]);
}

/**
* '?' and '%%' inside string literals reach the database as plain text.
*
* @return void
* @throws Exception
*/
public function testPlaceholderCharactersInStringLiteralsExecute(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$Statement->sql("SELECT 'Why?' AS `q`, ? AS `v`, '100%%' AS `p`;")->bStr('x');

$this->assertEquals(['q' => 'Why?', 'v' => 'x', 'p' => '100%%'], $this->db->selectRow($Statement));
}

/**
* Two '%%' placeholders in one sql() call each get their own value.
*
* @return void
* @throws Exception
*/
public function testTwoRawPlaceholdersInOneSqlCallExecute(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$Statement->sql('SELECT %% AS `a`, %% AS `b`;')->bFloat(1, 1)->bFloat(2, 1);

$this->assertEquals(['a' => '1.0', 'b' => '2.0'], $this->db->selectRow($Statement));
}

/**
* A "-- comment" in one sql() call must not comment out the calls after it.
*
* @return void
* @throws Exception
*/
public function testLineCommentDoesNotSwallowLaterSqlCalls(): void
{
$Statement = new GLPDO2\Statement(GLPDO2\Bindings\MySQL\MySQLBindingFactory::build());

$Statement
->sql('SELECT `name`')
->sql('FROM `test` -- which location?')
->sql('WHERE `location` = ?;')->bStr('Estonia');

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

// Insert

/**
Expand Down
120 changes: 120 additions & 0 deletions tests/StatementPlaceholderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php

namespace GeekLab\GLPDO2;

use GeekLab\GLPDO2\Bindings\MySQL\MySQLBindingFactory;
use PHPUnit\Framework\TestCase;

/**
* '?' and '%%' are placeholders only outside quoted strings, backtick identifiers and comments.
* These tests only build statements, so no database is needed.
*/
class StatementPlaceholderTest extends TestCase
{
private function statement(): Statement
{
return new Statement(MySQLBindingFactory::build());
}

/**
* @return array<string, array{string}>
*/
public static function untouchedProvider(): array
{
return [
'single-quoted string' => ["SELECT 'Why?'"],
'double-quoted string' => ['SELECT "Why?"'],
'backtick identifier' => ['SELECT `odd?name` FROM t'],
'doubled quote escape' => ["SELECT 'It''s ok?'"],
'backslash escaped quote' => ["SELECT 'a\\'b?'"],
'escaped backslash at end' => ["SELECT 'a\\\\', 'b?'"],
'percent pair in string' => ["SELECT * FROM t WHERE a LIKE '%%'"],
'dash dash comment' => ['SELECT 1 -- why? %%'],
'hash comment' => ['SELECT 1 # why? %%'],
'block comment' => ['SELECT 1 /* why? %% */'],
'quote inside comment' => ["SELECT 1 /* it's? */"],
'comment marker in string' => ["SELECT '-- ?', '# ?', '/* ?'"],
];
}

/**
* @dataProvider untouchedProvider
*/
public function testPlaceholderCharactersInLiteralsAndCommentsAreLeftAlone(string $sql): void
{
$this->assertSame($sql, $this->statement()->sql($sql)->getComputed());
}

public function testPlaceholdersAroundLiteralsStillWork(): void
{
$statement = $this->statement()
->sql("SELECT ?, 'Why?', ?")->bInt(1)->bStr('x');

$this->assertSame("SELECT 1, 'Why?', 'x'", $statement->getComputed());
}

public function testRawPlaceholderInBackticksNamesATable(): void
{
$statement = $this->statement()->sql('SELECT `col?` FROM `%%`')->bRaw('test');

$this->assertSame('SELECT `col?` FROM `test`', $statement->getComputed());
}

public function testTwoRawPlaceholdersInOneSqlCallGetTheirOwnValues(): void
{
$statement = $this->statement()->sql('VALUES (%%, %%)')->bFloat(1)->bFloat(2);

$this->assertSame('VALUES (1.000, 2.000)', $statement->getComputed());
}

public function testRawAndPositionalPlaceholdersMixedInOneSqlCall(): void
{
$statement = $this->statement()
->sql('SELECT ? FROM `%%` WHERE a IN (%%) AND b = ?')
->bInt(1)->bRaw('t')->bIntArray([4, 5])->bStr('x');

$this->assertSame("SELECT 1 FROM `t` WHERE a IN (4, 5) AND b = 'x'", $statement->getComputed());
}

public function testPlaceholderAfterBlockCommentWorks(): void
{
$statement = $this->statement()->sql('SELECT /* ? */ ?')->bInt(7);

$this->assertSame('SELECT /* ? */ 7', $statement->getComputed());
}

public function testDashDashWithoutSpaceIsNotAComment(): void
{
// MySQL reads "1--?" as 1 minus minus the value, not as a comment.
$statement = $this->statement()->sql('SELECT 1--?')->bInt(2);

$this->assertSame('SELECT 1--2', $statement->getComputed());
}

public function testStringSpanningSqlCallsIsTracked(): void
{
$statement = $this->statement()
->sql("SELECT 'start")
->sql("still a string?'")
->sql(', ?')->bInt(3);

$this->assertSame("SELECT 'start\nstill a string?'\n, 3", $statement->getComputed());
}

public function testLineCommentEndsWithItsSqlCall(): void
{
$statement = $this->statement()
->sql('SELECT 1 -- note?')
->sql('+ ?')->bInt(4);

$this->assertSame("SELECT 1 -- note?\n+ 4", $statement->getComputed());
}

public function testResetClearsAnOpenString(): void
{
$statement = $this->statement()->sql("SELECT 'unterminated");
$statement->reset()->sql('SELECT ?')->bInt(5);

$this->assertSame('SELECT 5', $statement->getComputed());
}
}
Loading