0

I'm writing a bit of code that will add links to a page based on whether a cell called "cityname_1" is filled in a SQL table called "state_info". I've been able to use this kind of if statement to insert links to anchors on the page using normal html within the php template, but now I'd like to insert links to other pages based on the contents of these SQL cells.

For the purposes of this code, I want to create a link to a page on our site with the URL style: /state-name/city-name/, and the link text would be the city name.

Here's the code for which I'm getting an error:

<?php 
if ( 0 !== strlen($state_info->cityname_1) ) {
    echo "<a class='stateNavLink' href='/"<?php echo $state_info->state_slug; ?>"/"<?php echo $state_info->cityslug_1; ?>"/'>"<?php echo $state_info->cityname_1; ?>"</a>";

} 
?>

So if the cell has contents, the output should basically be:

<a class="stateNavLink" href="/state-name/city-name">City Name</a>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Benzy
  • 15
  • 4
  • you should have gotten back an `unexpected T_ECHO` had you error reporting set. Or it's what you left out in your post seeing you've gotten an error back as you stated. – Funk Forty Niner Jul 17 '18 at 22:22

1 Answers1

1

You've got nested echo commands, which is unnecessary and causing problems.

Your code should just be:

echo "<a class='stateNavLink' href='/" . $state_info->state_slug . "/" . $state_info->cityslug_1 . "/'>" . $state_info->cityname_1 . "</a>";

Or, for extra style points, you can use interpolation:

echo "<a class='stateNavLink' href='/{$state_info->state_slug}/{$state_info->cityslug_1}/'>{$state_info->cityname_1}</a>";
random_user_name
  • 25,694
  • 7
  • 76
  • 115