I can't really find good guidelines through Google searches of the proper way to escape variables in URLs. Basically I am printing out a bunch of results from a MySQL query in a table, and I want one of the entries in each row to be a link to that result's page. I think this is easy, that I'm just missing a apostrophe or backslash somewhere, but I can't figure it out. Here's the line that's causing the error:
echo "<a href = \"movies.php/?movie_id='$row['movie_id']'\"> Who Owns It? </a> ";
and this is the error I'm getting:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING
How do I fix this error?
In addition, what are some general guidelines for working with echo and variables in URLs?
echo "<a href = \"movies.php/?movie_id='$row['movie_id']'\"> Who Owns It? </a> ";
There are two things here that should be changed. For one thing there shouldn't be a / after movies.php. The second is that there aren't any apostrophies around url variables. It should be movie_id=$row['movie_id']. Whenever I use a php variable I usually concatonate it instead of embed it in the quotations. So in the end I'd do something like this:
echo "<a href=\"movies.php?movie_id=" . $row['movie_id'] . "\"> Who Owns It? </a>";
The $row['movie_id']
inside the double quoted string is not allowed (especially the single quotes). Either write it without '
or use the curly braces syntax:
echo "<a href = \"movies.php/?movie_id='$row[movie_id]'\"> Who Owns It? </a> ";
echo "<a href = \"movies.php/?movie_id='{$row['movie_id']}'\"> Who Owns It? </a> ";
See variable parsing for further information.
This is a better way:
$movie_id = urlencode($row["movie_id"]);
echo '<a href="movies.php/?movie_id=', $movie_id, '"> Who Owns It? </a> ';
Good luck!
This is a better(er) way:
$movie_id = urlencode($row["movie_id"]);
echo "<a href=\"movies.php?movie_id={$movie_id}\"> Who Owns It? </a> ";
Easier to read. Besides the single and double quote speed thing is not much of an issue any more.
Echo or URLs have nothing to do with your problem. It's PHP strings syntax.