php参数化SQL查询特殊运算符

时间:2012-11-21 11:38:31

标签: php sql operators sql-injection parameterized-query

我碰巧看到以下方法来组成参数化SQL查询:

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));
}

在此处重述我的问题:

  • 符号“<<<”的作用是什么?
  • 我的同事说'SQL_STR'必须匹配,为什么?

2 个答案:

答案 0 :(得分:3)

Heredoc用于定义字符串,通常是因为不需要在字符串中转义引号,这与字符串文字不同。

来自Manual

  

Heredoc文本的行为就像双引号字符串,没有双引号。这意味着heredoc中的引号不需要转义,但仍可以使用上面列出的转义码。变量被扩展,但在heredoc中用字符串表示复杂变量时必须同样谨慎。

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

答案 1 :(得分:1)

您所寻找的内容称为heredoc

对于它的价值,SQL查询与字符串赋值无关:

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

当然也不限于HTML。它对于大块文本有很多有用的属性。也就是说,您可以以愉快的方式将变量插入到其中,并且您不必转义单引号或双引号。 (根据手册:“Heredoc文本的行为就像双引号字符串,没有双引号。”)