Search code examples
phpsqloperatorssql-injectionparameterized-query

php parameterized SQL query special operator


I just happened to see the following way to compose a parameterized SQL query:

function select_user($uid)
{
    // what is '<<<'?  
    // I can't google any document about it
    // (or I don't know how to search symbol)

    $sqlStr = <<< SQL_STR

         SELECT * FROM user WHERE uid = ?

SQL_STR; // must put in the begin of the line
         // and it must match the word at the right hand side of '= <<<'

    // Code Igniter Database Class
    return $this->db->query($sqlStr, array($uid));
}

To rephrase my questions in here:

  • What the symbol '<<<' does?
  • My colleague said that 'SQL_STR' must be matched, why?

Solution

  • What your looking for is called heredoc.

    For what it's worth, the SQL query is irrelevant to the string assignment:

    $html = <<<HTML
        Imagine some HTML here with interspersed $variables
    HTML;
    

    It's of course not limited to HTML either. It has quite a few useful properties for large blocks of text. Namely, you can interpolate variables into it in a pleasant manner, and you don't have to escape single or double quotes. (According to the manual: "Heredoc text behaves just like a double-quoted string, without the double quotes.")