Search code examples
phpechohref

PHP: trying to put href HTML attribute into a `echo`


I can't seem to get a URL into echo. I want to make a link to open Google Maps:

enter image description here

I can't figure out what's wrong with my code:

$query = mysql_query("SELECT * FROM cev")or die(mysql_error());
while($row = mysql_fetch_array($query))
{
  $name = $row['sitecode'];
  $lat = $row['latitude'];
  $lon = $row['longitude'];
  $type = $row['sitetype']; 
  $city = $row['city']; 
  $id = $row['id'];

  echo("addMarker($lat, $lon,'<b>$name</b><a href="editcev.php?id=' . $row['id'] . '">View</a><br><br/>$type<br/>$city');\n");

Solution

  • You have to fix the quotes:

     echo "addMarker($lat, $lon,'<b>$name</b><a href=\"editcev.php?id={$row['id']}\">View</a><br><br/>$type<br/>$city');\n";
    

    Alternative ways

    Here document

    echo <<<EOS
    addMarker($lat, $lon, '<b>$name</b><a href="editcev.php?id={$row['id']}">View</a><br><br/>$type<br/>$city');
    
    EOS;
    

    Concatenation

    echo "addMarker($lat, $lon, '<b>$name</b>" .
      "<a href=\"editcev.php?id={$row['id']}\">View</a>" .
      "<br><br/>$type<br/>$city)";
    

    Using addshashes

    The addMarker looks like a JavaScript function. You might pre-process the HTML string by means of addslashes:

    $html = <<<EOS
    <b>$name</b><a href="editcev.php?id={$row['id']}">View</a><br><br/>$type<br/>$city
    EOS;
    $html = addslashes($html);
    
    echo "addMarker($lat, $lon, '$html');\n";
    

    Recommendations

    I recommend using an editor with support of syntax highlighting.

    Read about PHP strings. Especially the matter of escaping.

    Finally, I wouldn't recommend writing any HTML/JavaScript within a PHP code. Use template engines such as Smarty or Twig instead.