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

问题描述 投票:33回答:1

我是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);

        // Then I read the data in the database '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());
    }
?>
php sql variables heredoc
1个回答
86
投票

您的heredoc需要进行一些修改(因为它实际上是Nowdoc!):

    echo <<<EX
    <p>Game: {$data['game_name']}<br/>
    the owner of the game is {$data['game_owner']}
    </p>
EX;
  • Heredoc标识符(与nowdoc的标识符不同)不能被引用。 'EX'需要成为EX
  • Heredoc终止符不得前面有空格。从文档中:

    非常重要的一点是,带有结束标识符的行不能包含其他任何字符,除了分号(;)之外。

    您正在将Nowdoc与heredoc混淆。

  • 字符串中的复杂数据类型必须用{}括起来,才能将它们解析为变量。例如,$data['game_name']应为{$data['game_name']}

[您在这里混淆了这里doc和现在的doc。您想使用heredocnot Nowdoc,因为您的字符串中包含变量。 Heredocs是“扩展”双引号字符串,而nowdocs更类似于单引号字符串,因为变量不是在nowdoc字符串中解析,而是在heredoc中解析。

  • 更多关于heredoc here
  • 更多关于Nowdoc here

请详细阅读文档。

© www.soinside.com 2019 - 2024. All rights reserved.