Ronald
Ronald

Reputation: 557

Html and PHP Concatenation in URL String

Whats wrong with this HTML / PHP - just doesnt look right - Is there a better way to concatenate html and php variables into url string ???

<a href="movie_night_del.php?id=<?php echo $id ?>&mov=<?php echo $mov ?>">Click here to delete</a>

Upvotes: 1

Views: 4522

Answers (2)

hywak
hywak

Reputation: 919

I prefer to do it in "more php" way, for example:

echo '<a href="movie_night_del.php?id=' . $id . '&mov=' . $mov . '">Click here to delete</a>'
//or
echo "<a href='movie_night_del.php?id={$id}&mov={$mov}'>Click here to delete</a>"
//or escaping "
echo "<a href=\"movie_night_del.php?id={$id}&mov={$mov}\">Click here to delete</a>"

Upvotes: 2

jeroen
jeroen

Reputation: 91792

As mentioned in the comments, there is nothing wrong doing it like that but your values could break the query string if they contain characters that need to be encoded.

For example the & and the = have special meanings, so if they could appear in your variable values, they would break the query string.

You can escape individual values using:

... &mov=<?php echo urlencode($mov) ?> ....

Or you could have php build and encode your string automatically using http_build_query:

$data = array(
  'id' => $id,
  'mov' => $mov
);
$url = 'movie_night_del.php?' . http_build_query($data);

Perhaps the last option is what you were looking for.

Upvotes: 1

Related Questions