首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中使用heredoc中的变量(SQL实践)

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

Stack Overflow用户
提问于 2012-06-30 21:16:45
回答 1查看 54.3K关注 0票数 43

我是PHP/SQL的新手,我正在尝试在text文档中使用一个变量,因为我需要输出大量的文本。我只包含了第一句话,因为它足以说明问题)。

我的问题是,在此处文档中,变量(见下文:$data['game_name]$data['game_owner'])不被识别为变量,而是被识别为纯文本。我该如何解决这个问题呢?

代码语言:javascript
复制
<?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());
    }
?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-30 21:21:26

您的heredoc需要稍微修改一下(因为它实际上是Nowdoc!):

代码语言:javascript
复制
    echo <<<EX
    <p>Game: {$data['game_name']}<br/>
    the owner of the game is {$data['game_owner']}
    </p>
EX;

不能用引号引用

  • Heredoc标识符(与nowdoc不同)。在此,EX.
  • The需要成为'EX'终止符,前面不能有任何空格。从文档中:

请务必注意,带有结束标识符的行除分号(;)外,不得包含其他字符。

你把Nowdoc和heredoc搞混了。

字符串中的

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

你把这里的医生和现在的医生搞混了。你想在这里使用,got,,而不是Nowdoc,因为你的字符串中有变量。Heredocs是“扩展的”双引号字符串,而nowdocs更类似于单引号字符串,因为变量不是在nowdoc字符串中解析的,而是在more文档中。

here.

  • More on Nowdoc here.

上的

  • More on heredoc

请仔细阅读这些文档。

票数 105
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11274354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档