dongyu4908 2012-06-30 13:16
浏览 46
已采纳

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

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

My problem is that within the heredoc, the variables (see below: $data['game_name] and $data['game_owner']) are not recognized as a variable 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);
    //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());
}
?>

Any help would be much appreciated.

  • 写回答

1条回答 默认 最新

  • dongque1462 2012-06-30 13:21
    关注

    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 identifiers (unlike nowdoc ones) cannot be quoted. 'EX' needs to become EX.
    • The Heredoc terminator must not have any preceding whitespace. From the docs:

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

      You're confusing Nowdoc with Heredoc.

    • Complex data types in strings must be surrounded by {} for them to be parsed as variables. For example, $data['game_name'] should be {$data['game_name']}.

    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.

    • More on Heredoc here.
    • More on Nowdoc here.

    Please read the documentation more carefully on these.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备