Skip to content
Open
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
8 changes: 7 additions & 1 deletion src/Pg.php
Original file line number Diff line number Diff line change
Expand Up @@ -460,14 +460,20 @@ protected function replaceBind(string &$preparedQuery, Bind $bind): void
}

/**
* Replaces named placeholder with its value.
*
* Trailing (\W|$) keeps :id from being replaced inside :idAccount, but,
* unlike a mandatory (\W), matches a placeholder standing at the very end
* of the query as well.
*
* @param $name
* @param $value
* @param $subject
* @return string|string[]|null
*/
private function _replaceBind($name, $value, $subject)
{
return preg_replace('~' . $name . '(::\w+)?(\W)~', sprintf("%s$1$2", $value), $subject);
return preg_replace('~' . $name . '(::\w+)?(\W|$)~', sprintf("%s$1$2", $value), $subject);
}

/**
Expand Down
39 changes: 39 additions & 0 deletions tests/Pg/PgBindTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,43 @@ public function testBind()
self::assertSame('1.00011122', $row['sixes']);
self::assertSame('{foo,bar,false,NULL}', $row['array_of_text']);
}

/**
* Placeholder standing at the very end of the query must be replaced too.
*
* @throws DBDException
* @throws Exception
*/
public function testBindAtTheEndOfQuery()
{
$sth = $this->db->prepare("SELECT :int AS num WHERE 'some string' = :string");
$sth->bind(':int', 1, NumericPrimitives::Int16)
->bind(':string', 'some string');

$sth->execute();
$row = $sth->fetchRow();

self::assertIsArray($row);
self::assertEquals(1, $row['num']);
}

/**
* Shorter bind name must not be replaced inside a longer one.
*
* @throws DBDException
* @throws Exception
*/
public function testBindNameIsPrefixOfAnother()
{
$sth = $this->db->prepare("SELECT :id AS first, :idAccount AS second");
$sth->bind(':id', 'one')
->bind(':idAccount', 'two');

$sth->execute();
$row = $sth->fetchRow();

self::assertIsArray($row);
self::assertSame('one', $row['first']);
self::assertSame('two', $row['second']);
}
}