Samuel Sjöberg's weblog

Skip to navigation

SQL statements continued

I realized my faked prepared statements don't work today. As soon as the string contains a questionmark the implementation breaks.

How to fix this? Well, by making sure we don't search for questionmarks in the inserted strings... strpos has a nice additional argument that defines the offset from where to start searching. This makes it pretty easy to solve the problem by introducing an offset counter. The DB::_prepare method now looks like this (changes marked in red):

function _prepare($statement, $value) {
    $value = $this->escape($value);
    if (!is_numeric($value)) {
        $value = "'$value'";
    $pos = strpos($statement, '?', $this->offset);
    $this->offset = $pos + strlen($value);
    return substr_replace($statement, $value, $pos, 1);

The methods that invoke the internal DB::_prepare function clears the offset variable before they start building a new statement. This effectivly stops questionmarks from messing up the statements.

Pages linking to this entry

Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.

About this post

Created 17th March 2007 17:07 CET. Filed under PHP.

0 Pingbacks