在PHP中的Heredoc中使用变量(SQL练习) [英] Use a variable within heredoc in PHP (SQL practice)

查看:277
本文介绍了在PHP中的Heredoc中使用变量(SQL练习)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP/SQL的新手,由于要输出大量文本,因此我试图在Heredoc中使用变量.我只添加了第一句话,因为它足以显示问题.

I'm a newbie to PHP/SQL and I am trying to use a variable within a heredoc as I need to output a lot of text. I've only included the first sentence as it is enough to show the problem).

我的问题是在Heredoc中,变量(请参见以下内容:$data['game_name]$data['game_owner'])不能识别为变量,而可以识别为纯文本.我该如何解决?

My problem is that within the heredoc, the variables (see below: $data['game_name] and $data['game_owner']) are not recognized as variables, but as plain text. How can I solve this?

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

推荐答案

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

Your heredoc needs a little modification (because it's actually 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终止符一定不能具有任何前面的空格.从文档中:

    • Heredoc identifiers (unlike nowdoc ones) cannot be quoted. 'EX' needs to become EX.
    • The heredoc terminator must not have any preceding whitespace. From the documentation:

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

      It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;).

      您正在将Nowdoc与heredoc混淆.

      You're confusing Nowdoc with heredoc.

      您正在将heredoc和nowdoc混在一起.您想使用 heredoc not Nowdoc,因为您的字符串中包含变量. Heredocs是扩展"双引号字符串,而nowdocs更类似于单引号字符串,因为变量不是在nowdoc字符串中解析,而是在heredoc中.

      You're mixing up heredoc and nowdoc here. You want to use heredoc and not Nowdoc because you've got variables inside your string. Heredocs are "extended" double quoted strings, whereas nowdocs are more akin to a single quoted string, in that variables are not parsed in nowdoc strings, but are in heredoc.

      • 有关heredoc的更多信息这里.
      • 有关Nowdoc的更多信息这里.
      • More on heredoc here.
      • More on Nowdoc here.

      请更仔细地阅读文档.

      这篇关于在PHP中的Heredoc中使用变量(SQL练习)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆