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).
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());
}
?>
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;
'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 (;).
You're confusing Nowdoc with heredoc.
{}
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.
Please read the documentation more carefully on these.