Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Abe Layee
Abe Layee
8,378 Points

NEED HELP

I am trying to print out the user id in the url, but I keep getting this error "syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) ". Thank you

    $query = "SELECT  * FROM employees ";
    $query = mysqli_query($connect,$query);

    while($row= mysqli_fetch_array($query)) {
      echo '<div>';
      echo "<a href='profile.php?userId = <?php echo $row['id'];?>'>"; // error is here.. it should print out the user id in the url
      echo  $row['firstName'] . "  ". "  ".$row['lastName'];
      echo '</a>';
      echo '</div>';
   }

2 Answers

Hello Abe Layee,

Your error is because you have a string syntax error. See PHP Strings Documentation

TLDR:

It appears "<?php echo $row['id'];?>" is copy from another project/ stack overflow without trying to understand what it does or how it works.

Issues:

  • Your query string cannot have spaces.
  • before closing the string you have <?php echo, which should not be in the string.
  • You cannot execute php within a string

Your code:

<?php echo "<a href='profile.php?userId = <?php echo $row['id'];?>'>";

Quick fix:

<?php echo "<a href='profile.php?userId={$row['id']}>";

Recommended Solution:

I would recommend using http_build_query since it will help you escape values and allows you to build complex query strings with ease. It is more readable and performant to echo once, so I combined statements and renamed variables to better describe their use.

<?php
while ($row = mysqli_fetch_array($query)) {
    $href = 'profile.php?'.http_build_query([
        'userId' => $row['id'],
    ]);
    $anchorText = $row['firstName'].' '.$row['lastName'];
    echo "<div><a href=\"{$href}\">{$anchorText}</a></div>";
}
Abe Layee
Abe Layee
8,378 Points

I got it... thank