0

Im sure this is an easy error for some of you to solve but it always confuses me, can someone help me with which way i should be writing this line of code:

echo '<a href="$db_field['ProductLink'] '/> . $db_field['ProductName'] . '</a>";

i think it's the quotations that are catching me out. i'm getting the error unexpected T_STRING, expecting ',' or ';' ive tried moving the format around with no joy.

Ricky
  • 77
  • 1
  • 4
  • 14

6 Answers6

0
 echo '<a href="'.$db_field['ProductLink'].'">' . $db_field['ProductName'] . '</a>";
P0ZiTR0N
  • 612
  • 4
  • 9
0
echo '<a href="'.$db_field['ProductLink'].'"/>'.$db_field['ProductName'].'</a>';
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
0

This will work:

echo '<a href="' . $db_field['ProductLink'] . '"/>' . $db_field['ProductName'] . '</a>';

You might also want to use htmlspecialchars() on the product name.

MrCode
  • 63,975
  • 10
  • 90
  • 112
0
echo '<a href="' . $db_field['ProductLink'] . '">' . $db_field['ProductName'] . '</a>';
0

You have two options, you can use concatenation operators or use double quotes.

Option 1 (more readable):

echo "<a href='{$db_field['ProductLink']}'>{$db_field['ProductName']}</a>";

Option 2:

echo '<a href="' . $db_field['ProductLink'] . '">' . $db_field['ProductName'] . '</a>';

Just remember you need to have matching quotation marks everywhere. If you open one you have to close it.

Jordan Doyle
  • 2,976
  • 4
  • 22
  • 38
0

When working with other people or making your code public, you should always either be consistent or adhere to accepted coding standards for that project. In my experience, programmers prefer that you be consistent above all else as it's easier to switch to accepted standards if needed.

Using only variable interpolation:

echo "<a href=\"{$db_field['ProductLink']}\"/>{$db_field['ProductName']}</a>";

Using only concatenation:

echo '<a href="' . $db_field['ProductLink'] . '"/>' . $db_field['ProductName'] . '</a>';

It really comes down to personal preference, how public your code is, the coding standards on your team, etc. I have found that if you do variable interpolation, use the {}'s notation. It seems to be more accepted and it has the advantage of better syntax highlighting and the ability to interpolate array elements.

Additionally, though unrelated to the question you are asking, make sure that $db_field['ProductName'] has been sanitized with htmlentities() either before being stored, or being output to the browser. It is crucial that you be consistent in whichever strategy you use to prevent possible exploits or mistakes if other people work on your code.

There are some really good answers to this question if you need a good overview of using interpolation vs. concatenation. Someone also touches on the security aspects I mentioned above.

Community
  • 1
  • 1