I need a php variable to be placed in a href link

Asked

Viewed 36 times

0

The variable $fa has to be placed inside the link, but I can’t do it

This variable takes a database data, it is inside php code

$fa=$aux["celular"];

<a href = "https://///////////phone=$fa&text="> CLIQUE</a>
  • You need to open php tags or echo.

2 answers

1

Just interpolate the strings:

echo "<a href='http://...?phone={$phone}'></a>";

Notice the use of {$phone} within the string, which will be replaced by the variable value $phone.

But there are other considerations to be made. For example, what would happen to the value of $phone possess the character &, type "0000&0000"? The output generated would be:

<a href='http://...?phone=0000&0000'></a>

So the value of phone, in the URL, would it be "0000&0000" or just "0000"? To avoid unexpected behavior, you need to encode the value before sending it to the URL:

$phone = urlencode($phone);
echo "<a href='http://...?phone={$phone}'></a>";

Yeah, this way, the way out would be:

<a href='http://...?phone=0000%260000'></a>

Note that the character & was coded to %26 and thus the value of phone in the URL will be exactly "0000&0000", as expected.

If the HTML element is not the result of a PHP expression, you can use <?= ?> to show the value of the variable:

<a href='http://...?phone=<?= $phone ?>'></a>

That would be the equivalent of doing <?php echo $phone; ?>, but in a simpler way.

0

If you’re putting html echo in php, consider doing so by concatenating:

<?php
   $fa=$aux["celular"];
   echo '<a href = "https://///////////phone='.$fa.'&text=">CLIQUE</a>';
?>

If you’re putting php in html, consider this way:

<?php
   $fa=$aux["celular"];
?>
<a href = "https://///////////phone=<?php echo $fa; ?>&text=">CLIQUE</a>';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.