Skip to content

PREG_QUOTE and SQL String Binding #655

Description

@JakeAi

The function \CodeIgniter\Database\Query matchNamedBinds() uses preg_quote to escape some characters. This is a hindrance with SQLSRV as the backslashes are taken literally. Is there a way to override this function in the driver since it's being loaded as a new query in many base functions?

Adding the line (below) fixes the issue.

$escapedValue = str_replace('\\-', '-', $escapedValue);
protected function matchNamedBinds(string $sql, array $binds)
	{
		foreach ($binds as $placeholder => $value)
		{
			$escapedValue = $this->db->escape($value);
			// In order to correctly handle backlashes in saved strings
			// we will need to preg_quote, so remove the wrapping escape characters
			// otherwise it will get escaped.
			if (is_array($value))
			{
				foreach ($value as &$item)
				{
					$item = preg_quote($item, '|');
				}
				$escapedValue = '(' . implode(',', $escapedValue) . ')';
			}
			else
			{
				$escapedValue = preg_quote(trim($escapedValue, $this->db->escapeChar), '|');
			}
			// preg_quoting can cause issues with some characters in the final query,
			// but NOT preg_quoting causes other characters to be intepreted, like $.
			$escapedValue = str_replace('\\.', '.', $escapedValue);

			//THIS LINE FIXES IT
			$escapedValue = str_replace('\\-', '-', $escapedValue);
			//THIS LINE FIXES IT

			$sql = preg_replace('|:' . $placeholder . '(?!\w)|', $escapedValue, $sql);
		}
		return $sql;
	}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions