在PHP中使用heredoc中的变量(SQL实践)

Mat*_*ieu 33 php sql variables heredoc

我是PHP/SQL的新手,我试图在heredoc中使用变量,因为我需要输入大量文本.我只包括第一句话,因为它足以显示问题).

我的问题是在heredoc中,变量(见下文:$data['game_name]$data['game_owner'])不被识别为变量而是纯文本.我怎么解决这个问题?

<?php
try
{
    //i am connecting the the database base mysql 'test'
    $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
    $bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '', $pdo_options);
    //the i read the data in the databse 'video_dame'
    $response = $bdd->query('SELECT * FROM video_game');
    //pour qu'elle soit visible à l'écran, on affiche chaque entrée une à une
    while ($data= $response->fetch())
    {
    echo <<<'EX'
    <p>Game: $data['game_name]<br/>
    the owner of the game is $data['game_owner']
    </p>
    EX;
    }
    //i end the sql request
    $response->closeCursor();
}
catch (Exception $e)
{
    die('Error: '.$e->getMessage());
}
?>
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激.

Boj*_*les 83

你的Heredoc需要一点修改(因为它实际上是Nowdoc!):

    echo <<<EX
    <p>Game: {$data['game_name']}<br/>
    the owner of the game is {$data['game_owner']}
    </p>
EX;
Run Code Online (Sandbox Code Playgroud)
  • 不能引用Heredoc标识符(与nowdoc标识符不同).'EX'需要成为EX.
  • Heredoc终结符必须没有任何前面的空格.来自文档:

    请注意,具有结束标识符的行必须不包含其他字符,除了可能是分号(;)之外,这一点非常重要.

    你对Nowdoc和Heredoc感到困惑.

  • 必须包围字符串中的复杂数据类型,{}以便将它们解析为变量.例如,$data['game_name']应该是{$data['game_name']}.

你在这里混合了heredoc和nowdoc.你想使用Heredoc不是 Nowdoc,因为你的字符串中有变量.Heredocs是"扩展"双引号字符串,而nowdocs更类似于单引号字符串,因为变量不在nowdoc字符串中解析,而是在heredoc中.

  • 更多关于Heredoc的信息.
  • 更多关于Nowdoc的信息.

请仔细阅读文档.