From add4e4c1335609d352ca1002ad6ae86a15cfc880 Mon Sep 17 00:00:00 2001 From: ellisgl Date: Wed, 25 Nov 2026 09:00:01 -0600 Subject: [PATCH 1/2] Leave ? and %% alone inside SQL string literals and comments Statement::sql() turned every ? and %% into a placeholder, so SQL such as WHERE note = 'Why?' broke. sql() now tracks quoted strings, backtick identifiers and comments, across sql() calls, and only replaces placeholders in SQL code. Inside backticks %% is still a placeholder, so `%%` with bRaw() can still name a table. execute() now joins sql() calls with newlines, as getComputed() already did, so a -- comment in one call no longer comments out the calls after it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + README.md | 2 +- src/Statement.php | 126 ++++++++++++++++++++++++----- tests/GLPDO2MySQLTest.php | 33 ++++++++ tests/StatementPlaceholderTest.php | 104 ++++++++++++++++++++++++ 5 files changed, 248 insertions(+), 21 deletions(-) create mode 100644 tests/StatementPlaceholderTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 971bcff..9d5effb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +Unreleased +* 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. +* 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. diff --git a/README.md b/README.md index ad34efc..5fd1fe3 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ Is there a transaction in progress, returns bool. ### Misc Methods Statement->sql(string $text)
-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()
Used to reset Statement private variables. Usefully for creating multiple queries without having to create a new Statement object. diff --git a/src/Statement.php b/src/Statement.php index c925eb7..299b785 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -27,6 +27,15 @@ 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). + + // 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 // */ @@ -350,9 +359,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); @@ -434,6 +443,9 @@ 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 * @@ -441,29 +453,101 @@ private function placeholderGetName(): string */ 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. * @@ -478,6 +562,8 @@ public function reset(): self $this->rawNamed = []; $this->rawPos = 0; $this->arrPos = 0; + $this->lexState = self::LEX_CODE; + $this->lexQuote = ''; // $this->rawSql = []; return $this; diff --git a/tests/GLPDO2MySQLTest.php b/tests/GLPDO2MySQLTest.php index 8a4ab98..21b87e7 100644 --- a/tests/GLPDO2MySQLTest.php +++ b/tests/GLPDO2MySQLTest.php @@ -1029,6 +1029,39 @@ 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)); + } + + /** + * 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 /** diff --git a/tests/StatementPlaceholderTest.php b/tests/StatementPlaceholderTest.php new file mode 100644 index 0000000..5953cd1 --- /dev/null +++ b/tests/StatementPlaceholderTest.php @@ -0,0 +1,104 @@ + + */ + 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 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()); + } +} From 0e8028e82319f7da210eafff634be1a830af5143 Mon Sep 17 00:00:00 2001 From: ellisgl Date: Wed, 25 Nov 2026 09:03:46 -0600 Subject: [PATCH 2/2] Give each %% placeholder in an sql() call its own value sql() named every %% with the current raw bind position without advancing it, so two %% in one sql() call got the same name and both were filled with the first raw value: sql('VALUES (%%, %%)') ->bFloat(1)->bFloat(2) produced VALUES (1.000, 1.000). %% now has its own counter, matched in order to the raw binds, as ? already is. Also sets the CHANGELOG and README "Latest" entries to 4.0.12. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- README.md | 7 ++++--- src/Statement.php | 7 +++++-- tests/GLPDO2MySQLTest.php | 15 +++++++++++++++ tests/StatementPlaceholderTest.php | 16 ++++++++++++++++ 5 files changed, 42 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d5effb..5fe5761 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ -Unreleased +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) diff --git a/README.md b/README.md index 5fd1fe3..d74bba2 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/Statement.php b/src/Statement.php index 299b785..54fd44e 100644 --- a/src/Statement.php +++ b/src/Statement.php @@ -25,7 +25,8 @@ class Statement * @var array{} | array $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. @@ -342,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++), @@ -561,6 +563,7 @@ 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 = ''; diff --git a/tests/GLPDO2MySQLTest.php b/tests/GLPDO2MySQLTest.php index 21b87e7..594d460 100644 --- a/tests/GLPDO2MySQLTest.php +++ b/tests/GLPDO2MySQLTest.php @@ -1044,6 +1044,21 @@ public function testPlaceholderCharactersInStringLiteralsExecute(): void $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. * diff --git a/tests/StatementPlaceholderTest.php b/tests/StatementPlaceholderTest.php index 5953cd1..116826e 100644 --- a/tests/StatementPlaceholderTest.php +++ b/tests/StatementPlaceholderTest.php @@ -60,6 +60,22 @@ public function testRawPlaceholderInBackticksNamesATable(): void $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);