« January 31, 2008 | Main | February 20, 2008 »

February 13, 2008 Archives

February 13, 2008

PHP 5.3 "NOWDOCS" make SQL escaping easier

<?php

// Escaping quotes or other meta characters in SQL can be painful
$sql[] = 'select sys_context(\'userenv\', \'service_name\') from dual';

// Unless you get lucky with your quoting style
$sql[] = "select sys_context('userenv', 'service_name') from dual";

// Escaping strings is even more annoying in XQUERY syntax which, when
// embedded in SQL, uses both single and double quotes and its own
// dollar-prefixed variables
$sql[] = 'select xmlquery(\'for $i in ora:view("hr","locations")/ROW
return $i/CITY\' returning content) from dual';
$sql[] = "select xmlquery('for \$i in ora:view(\"hr\",\"locations\")/ROW
return \$i/CITY' returning content) from dual";

// Even with PHP's "Heredoc" syntax something will need escaping.
// Note the final END can't have leading whitespace, nor trailing
// whitespace after the semi-colon
$sql[] = <<<END
select xmlquery('for \$i in ora:view("hr","locations")/ROW
return \$i/CITY' returning content) from dual
END;

// But with PHP 5.3's new "Nowdoc" syntax no escaping is needed.
// To distinguish a Nowdoc from a Heredoc, the initial keyword END is
// enclosed in single quotes.
$sql[] = <<<'END'
select xmlquery('for $i in ora:view("hr","locations")/ROW
return $i/CITY' returning content) from dual
END;

// Thanks Gwynne and Dmitry for the new feature!

$c = oci_pconnect('hr', 'hrpwd', 'localhost/orcl');

foreach ($sql as $stmt) {
    do_query($c, $stmt);
}

function do_query($c, $stmt)
{
    $s = oci_parse($c, $stmt);
    oci_execute($s);
    while ($row = oci_fetch_array($s, OCI_ASSOC)) {
        foreach ($row as $item) {
            echo "$item ";
        }
        echo "\n";
    }
}

?>

About February 2008

This page contains all entries posted to Christopher Jones on OPAL in February 2008. They are listed from oldest to newest.

January 31, 2008 is the previous archive.

February 20, 2008 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type and Oracle