i wrote the following code…
<?php
$conn=mysql_connect("localhost","","");
if($conn)
echo "connection established";
mysql_select_db("moviesite");
$que="select * from movie";
$result=mysql_query($que,$conn);
?>
<html>
<title>movie database</title>
<body>
<table border=1 align=center>
<th colspan=2>
PEOPLE<a href='movie.php?action=add & id='>[ADD]</a>
</th>
<?php
$ta_row=<<<eod
<tr>
<td>
$mov_name
</td>
<td>
<a href='movie.php?action=edit & id=$mov_id'>[EDIT]</a>
<a href='movie.php?action=delete & id=$mov_id'>[DELETE]</a>
<td>
</tr>
eod;
while($row=mysql_fetch_array($result))
{
$mov_id=$row["id"];
$mov_name=$row["name"];
echo $ta_row;
}
?>
now the above code didnt print the name or the id of the movie(the fields were blank)…so i cut and paste $ta_row inside the while loop after the definition of $mov_id and $mov_name…this sorted out all problems…but my question is why did the code fail earlier…as it is i was outputting ta_row after defining $mov_id and $mov_name so if $ta_row is just a string its content variables should have got changed…why didnt they change?
Because a heredoc is just like any other string – it’s value is fixed when you declare it. If the variables
$mov_idand$mov_nameweren’t set when you declared$ta_row, you can’t use them in$ta_row.If you want to do something like you tried to do in the first place, you would have to use something like
str_replace()orsprintf()– replace place-holders in the original string with the actual values you want to display.Consider this:
Now this:
…Heredocs behave exactly like a double-quoted string (from this point of view, at least).
Alternatively you could do this:
…because
$myVaris now single-quoted,$varappears in it literally. Then when you runstr_replace(), it is replaced with the value of$var, instead of the literal string.It’s probably worth you re-reading this.